ngram
listlengths 0
67.8k
|
|---|
[
"ans = K elif K <= A + B: ans = A else:",
"elif K <= A + B: ans = A else: ans = A",
"<= A: ans = K elif K <= A + B: ans =",
"K <= A + B: ans = A else: ans = A -",
"= sys.stdin.readline def main(): A, B, C, K = map(int, input().split()) if K",
"input().split()) if K <= A: ans = K elif K <= A +",
"A: ans = K elif K <= A + B: ans = A",
"else: ans = A - (K - (A + B)) print(ans) if __name__",
"ans = A - (K - (A + B)) print(ans) if __name__ ==",
"= map(int, input().split()) if K <= A: ans = K elif K <=",
"def main(): A, B, C, K = map(int, input().split()) if K <= A:",
"map(int, input().split()) if K <= A: ans = K elif K <= A",
"<= A + B: ans = A else: ans = A - (K",
"A, B, C, K = map(int, input().split()) if K <= A: ans =",
"input = sys.stdin.readline def main(): A, B, C, K = map(int, input().split()) if",
"K <= A: ans = K elif K <= A + B: ans",
"<filename>python/ABC/167/b.py import sys input = sys.stdin.readline def main(): A, B, C, K =",
"if K <= A: ans = K elif K <= A + B:",
"= A else: ans = A - (K - (A + B)) print(ans)",
"import sys input = sys.stdin.readline def main(): A, B, C, K = map(int,",
"K = map(int, input().split()) if K <= A: ans = K elif K",
"sys.stdin.readline def main(): A, B, C, K = map(int, input().split()) if K <=",
"sys input = sys.stdin.readline def main(): A, B, C, K = map(int, input().split())",
"main(): A, B, C, K = map(int, input().split()) if K <= A: ans",
"ans = A else: ans = A - (K - (A + B))",
"A else: ans = A - (K - (A + B)) print(ans) if",
"C, K = map(int, input().split()) if K <= A: ans = K elif",
"+ B: ans = A else: ans = A - (K - (A",
"= A - (K - (A + B)) print(ans) if __name__ == \"__main__\":",
"= K elif K <= A + B: ans = A else: ans",
"A - (K - (A + B)) print(ans) if __name__ == \"__main__\": main()",
"B, C, K = map(int, input().split()) if K <= A: ans = K",
"K elif K <= A + B: ans = A else: ans =",
"B: ans = A else: ans = A - (K - (A +",
"A + B: ans = A else: ans = A - (K -"
] |
[
"return self._code # TODO Use a setter ? def set_code(self, code): self._code =",
"def has_input(self, resource): return resource in self._inputs def input_urls(self): return {resource.url for resource",
"self._start = None self._end = None self._processor = processor self._filename = filename self._line_num",
"some output resources, some code that produces outputs from inputs, a processor that",
"\"\"\" self._start = None self._end = None self.log_stdout = None self.log_stderr = None",
"None self.log_stdout = None self.log_stderr = None self._success = None def static_check(self): \"\"\"",
"time() def set_end(self, success, error_msg): self._end = time() self._success = success self._error_message =",
"resources for this process exist, False otherwise \"\"\" result = [] for resource",
"\"\"\" def __init__(self, processor, filename, line_num): self._start = None self._end = None self._processor",
"in self._outputs: yield res def has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource):",
"__init__(self, processor, filename, line_num): self._start = None self._end = None self._processor = processor",
"process.iter_outputs(): if self.has_input(output_resource): return True return False def pick_an_output(self): if not self.has_outputs(): return",
"def success(self): return self._success @property def error_message(self): return self._error_message @property def processor(self): return",
"True return False def pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0] def",
"in process.iter_outputs(): if self.has_input(output_resource): return True return False def pick_an_output(self): if not self.has_outputs():",
"run()) from another process :param process: :return: \"\"\" self._start = process.start self._end =",
"sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process):",
"yield res def has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource): return resource",
"has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource): return resource in self._inputs def",
"input resources for this process exist, False otherwise \"\"\" result = [] for",
"from inputs, a processor that handle the language specificities \"\"\" def __init__(self, processor,",
"exist, False otherwise \"\"\" result = [] for resource in self.iter_outputs(): if not",
"assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not None self._reserved_path = reserved_path self.log_stdout",
"@property def success(self): return self._success @property def error_message(self): return self._error_message @property def processor(self):",
"in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls)",
"# TODO Use a setter ? def set_code(self, code): self._code = code @property",
"self._end = None self._processor = processor self._filename = filename self._line_num = line_num self._inputs",
"= process.start self._end = process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr =",
"success, error_msg): self._end = time() self._success = success self._error_message = error_msg def missing_outputs(self):",
"some input resources, some output resources, some code that produces outputs from inputs,",
"the properties set by function run()) from another process :param process: :return: \"\"\"",
"None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution info (all the",
"self._end = None self.log_stdout = None self.log_stderr = None self._success = None def",
"setter ? def set_code(self, code): self._code = code @property def success(self): return self._success",
"= process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info (all the properties set",
"self._success = success self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True if all",
"def error_message(self): return self._error_message @property def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res)",
"# -*- coding: utf8 -*- from time import time class Process: \"\"\" Class",
"code @property def success(self): return self._success @property def error_message(self): return self._error_message @property def",
"import time class Process: \"\"\" Class wrapping a process. A process has some",
"self._id @property def code(self): return self._code # TODO Use a setter ? def",
"code): self._code = code @property def success(self): return self._success @property def error_message(self): return",
"= None self._success = None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property",
"result = [] for resource in self.iter_outputs(): if not resource.exists(): result.append(resource) return result",
"def set_end(self, success, error_msg): self._end = time() self._success = success self._error_message = error_msg",
"self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res",
"= process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path =",
"return False def pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self,",
"start(self): return self._start @property def end(self): return self._end @property def id(self): return self._id",
"def missing_outputs(self): \"\"\" :return: True if all input resources for this process exist,",
"self._code = \"\" self.log_stdout = None self.log_stderr = None self._reserved_path = None self._success",
"for resource in self._inputs} def output_urls(self): return {resource.url for resource in self._outputs} def",
"None self._end = None self._processor = processor self._filename = filename self._line_num = line_num",
"execution info (all the properties set by function run()) from another process :param",
"specificities \"\"\" def __init__(self, processor, filename, line_num): self._start = None self._end = None",
"the resources produced by this process have been invalidated :return: \"\"\" self._start =",
"has_input(self, resource): return resource in self._inputs def input_urls(self): return {resource.url for resource in",
"self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info",
"= code @property def success(self): return self._success @property def error_message(self): return self._error_message @property",
"def reset_execution_info(self): \"\"\" Reset the execution info (all the properties set by function",
"because the resources produced by this process have been invalidated :return: \"\"\" self._start",
"processor self._filename = filename self._line_num = line_num self._inputs = [] self._outputs = []",
"the process won't obviously fail. This is used for static analysis before any",
"self._success = None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self):",
"= [] self._code = \"\" self.log_stdout = None self.log_stderr = None self._reserved_path =",
":return: \"\"\" self._start = process.start self._end = process.end self._success = process.success self.log_stdout =",
"def pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\"",
"False def pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process):",
"from another process :param process: :return: \"\"\" self._start = process.start self._end = process.end",
"def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not None self._reserved_path = reserved_path",
"processor, filename, line_num): self._start = None self._end = None self._processor = processor self._filename",
"This is used for static analysis before any process is run \"\"\" self._processor.static_check(self)",
"self._processor = processor self._filename = filename self._line_num = line_num self._inputs = [] self._outputs",
"that the process won't obviously fail. This is used for static analysis before",
"by function run()) because the resources produced by this process have been invalidated",
"self.log_stderr = None self._reserved_path = None self._success = None self._error_message = None self._id",
"error_msg def missing_outputs(self): \"\"\" :return: True if all input resources for this process",
"Copy the execution info (all the properties set by function run()) from another",
"add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs:",
"= log_stdout self.log_stderr = log_stderr def set_start(self): self._start = time() def set_end(self, success,",
"return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for",
"process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return False def pick_an_output(self):",
"utf8 -*- from time import time class Process: \"\"\" Class wrapping a process.",
"return len(self._outputs) > 0 def has_input(self, resource): return resource in self._inputs def input_urls(self):",
"process. A process has some input resources, some output resources, some code that",
"Use a setter ? def set_code(self, code): self._code = code @property def success(self):",
"(all the properties set by function run()) from another process :param process: :return:",
"None self._success = None def static_check(self): \"\"\" Runs a verification that the process",
"return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution info (all the properties",
"process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is",
"def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield res def",
"output_urls(self): return {resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for",
"reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self): self._start = time() def",
"return self._id @property def code(self): return self._code # TODO Use a setter ?",
"self._code = code @property def success(self): return self._success @property def error_message(self): return self._error_message",
"self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield res",
"if not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the",
"process :param process: :return: \"\"\" self._start = process.start self._end = process.end self._success =",
"error_message(self): return self._error_message @property def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def",
"iter_inputs(self): for res in self._inputs: yield res def iter_outputs(self): for res in self._outputs:",
"self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if self deprends on",
"\"\"\" Runs a verification that the process won't obviously fail. This is used",
"self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info (all the properties",
"output resources, some code that produces outputs from inputs, a processor that handle",
"process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution",
"process won't obviously fail. This is used for static analysis before any process",
"= None self._end = None self._processor = processor self._filename = filename self._line_num =",
"def id(self): return self._id @property def code(self): return self._code # TODO Use a",
"@property def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output)",
"self._error_message @property def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output):",
"self deprends on a resource created by process\"\"\" for output_resource in process.iter_outputs(): if",
"any process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path",
"None self._end = None self.log_stdout = None self.log_stderr = None self._success = None",
"sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\"",
"processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self):",
"in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if self deprends",
":return: True if all input resources for this process exist, False otherwise \"\"\"",
"self._end = time() self._success = success self._error_message = error_msg def missing_outputs(self): \"\"\" :return:",
"None def static_check(self): \"\"\" Runs a verification that the process won't obviously fail.",
"log_stderr): assert reserved_path is not None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr",
"= \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property def end(self): return self._end",
"run()) because the resources produced by this process have been invalidated :return: \"\"\"",
"for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if",
"\"\"\" result = [] for resource in self.iter_outputs(): if not resource.exists(): result.append(resource) return",
"produced by this process have been invalidated :return: \"\"\" self._start = None self._end",
"\",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if self deprends on a resource",
"process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info (all the",
"resources, some code that produces outputs from inputs, a processor that handle the",
"self._start = None self._end = None self.log_stdout = None self.log_stderr = None self._success",
"def iter_outputs(self): for res in self._outputs: yield res def has_outputs(self): return len(self._outputs) >",
"\"\"\" Class wrapping a process. A process has some input resources, some output",
"time() self._success = success self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True if",
"None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property def end(self):",
"{resource.url for resource in self._inputs} def output_urls(self): return {resource.url for resource in self._outputs}",
"self._filename = filename self._line_num = line_num self._inputs = [] self._outputs = [] self._code",
"None self.log_stderr = None self._success = None def static_check(self): \"\"\" Runs a verification",
":return: \"\"\" self._start = None self._end = None self.log_stdout = None self.log_stderr =",
"execution info (all the properties set by function run()) because the resources produced",
"res in self._outputs: yield res def has_outputs(self): return len(self._outputs) > 0 def has_input(self,",
"\"\"\" self._start = process.start self._end = process.end self._success = process.success self.log_stdout = process.log_stdout",
"return {resource.url for resource in self._inputs} def output_urls(self): return {resource.url for resource in",
"the properties set by function run()) because the resources produced by this process",
"= None self._success = None def static_check(self): \"\"\" Runs a verification that the",
"log_stdout, log_stderr): assert reserved_path is not None self._reserved_path = reserved_path self.log_stdout = log_stdout",
"process has some input resources, some output resources, some code that produces outputs",
"= sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns",
"def output_urls(self): return {resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url",
"\"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property def end(self): return self._end @property",
"outputs from inputs, a processor that handle the language specificities \"\"\" def __init__(self,",
"in self._inputs} def output_urls(self): return {resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls",
"the language specificities \"\"\" def __init__(self, processor, filename, line_num): self._start = None self._end",
"a process. A process has some input resources, some output resources, some code",
"self._line_num) @property def start(self): return self._start @property def end(self): return self._end @property def",
"process): \"\"\" Copy the execution info (all the properties set by function run())",
"= None def static_check(self): \"\"\" Runs a verification that the process won't obviously",
"analysis before any process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr):",
"another process :param process: :return: \"\"\" self._start = process.start self._end = process.end self._success",
"return self._success @property def error_message(self): return self._error_message @property def processor(self): return self._processor def",
"obviously fail. This is used for static analysis before any process is run",
"before any process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert",
"wrapping a process. A process has some input resources, some output resources, some",
"resource in self._inputs} def output_urls(self): return {resource.url for resource in self._outputs} def sorted_inputs_string(self):",
"missing_outputs(self): \"\"\" :return: True if all input resources for this process exist, False",
"? def set_code(self, code): self._code = code @property def success(self): return self._success @property",
"len(self._outputs) > 0 def has_input(self, resource): return resource in self._inputs def input_urls(self): return",
"{resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in",
"= reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self): self._start = time()",
"the execution info (all the properties set by function run()) because the resources",
"otherwise \"\"\" result = [] for resource in self.iter_outputs(): if not resource.exists(): result.append(resource)",
"class Process: \"\"\" Class wrapping a process. A process has some input resources,",
"@property def id(self): return self._id @property def code(self): return self._code # TODO Use",
"(all the properties set by function run()) because the resources produced by this",
"None self.log_stderr = None self._reserved_path = None self._success = None self._error_message = None",
"a resource created by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True",
"resources produced by this process have been invalidated :return: \"\"\" self._start = None",
"= None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return",
"set_start(self): self._start = time() def set_end(self, success, error_msg): self._end = time() self._success =",
"assert reserved_path is not None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr =",
"been invalidated :return: \"\"\" self._start = None self._end = None self.log_stdout = None",
"self.has_input(output_resource): return True return False def pick_an_output(self): if not self.has_outputs(): return None return",
"self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property def end(self): return",
"depends_on_process(self, process): \"\"\" Returns True if self deprends on a resource created by",
"this process exist, False otherwise \"\"\" result = [] for resource in self.iter_outputs():",
"\"\" self.log_stdout = None self.log_stderr = None self._reserved_path = None self._success = None",
"input_urls(self): return {resource.url for resource in self._inputs} def output_urls(self): return {resource.url for resource",
"self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution info",
"def __init__(self, processor, filename, line_num): self._start = None self._end = None self._processor =",
"def code(self): return self._code # TODO Use a setter ? def set_code(self, code):",
"resources, some output resources, some code that produces outputs from inputs, a processor",
"self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self): self._start =",
":param process: :return: \"\"\" self._start = process.start self._end = process.end self._success = process.success",
"pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy",
"in self._inputs def input_urls(self): return {resource.url for resource in self._inputs} def output_urls(self): return",
"log_stdout self.log_stderr = log_stderr def set_start(self): self._start = time() def set_end(self, success, error_msg):",
"self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property",
"not None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self):",
"static_check(self): \"\"\" Runs a verification that the process won't obviously fail. This is",
"self._line_num = line_num self._inputs = [] self._outputs = [] self._code = \"\" self.log_stdout",
"def end(self): return self._end @property def id(self): return self._id @property def code(self): return",
"produces outputs from inputs, a processor that handle the language specificities \"\"\" def",
"reserved_path, log_stdout, log_stderr): assert reserved_path is not None self._reserved_path = reserved_path self.log_stdout =",
"= [] self._outputs = [] self._code = \"\" self.log_stdout = None self.log_stderr =",
"resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return",
"= None self._reserved_path = None self._success = None self._error_message = None self._id =",
"0 def has_input(self, resource): return resource in self._inputs def input_urls(self): return {resource.url for",
"by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return False def",
"def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def",
"that handle the language specificities \"\"\" def __init__(self, processor, filename, line_num): self._start =",
"resource): return resource in self._inputs def input_urls(self): return {resource.url for resource in self._inputs}",
"in self._inputs: yield res def iter_outputs(self): for res in self._outputs: yield res def",
"self._success = process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def",
"verification that the process won't obviously fail. This is used for static analysis",
"won't obviously fail. This is used for static analysis before any process is",
"for res in self._inputs: yield res def iter_outputs(self): for res in self._outputs: yield",
"= time() def set_end(self, success, error_msg): self._end = time() self._success = success self._error_message",
"properties set by function run()) from another process :param process: :return: \"\"\" self._start",
"inputs, a processor that handle the language specificities \"\"\" def __init__(self, processor, filename,",
"return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if self deprends on a",
"self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self): self._start = time() def set_end(self,",
"def set_start(self): self._start = time() def set_end(self, success, error_msg): self._end = time() self._success",
"= \"\" self.log_stdout = None self.log_stderr = None self._reserved_path = None self._success =",
"res def iter_outputs(self): for res in self._outputs: yield res def has_outputs(self): return len(self._outputs)",
"fail. This is used for static analysis before any process is run \"\"\"",
"return {resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource",
"for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return False def pick_an_output(self): if",
"return self._start @property def end(self): return self._end @property def id(self): return self._id @property",
"a verification that the process won't obviously fail. This is used for static",
"end(self): return self._end @property def id(self): return self._id @property def code(self): return self._code",
"def depends_on_process(self, process): \"\"\" Returns True if self deprends on a resource created",
"def input_urls(self): return {resource.url for resource in self._inputs} def output_urls(self): return {resource.url for",
"self._inputs: yield res def iter_outputs(self): for res in self._outputs: yield res def has_outputs(self):",
"def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self,",
"= None self._processor = processor self._filename = filename self._line_num = line_num self._inputs =",
"> 0 def has_input(self, resource): return resource in self._inputs def input_urls(self): return {resource.url",
"self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield res def iter_outputs(self): for res",
"= processor self._filename = filename self._line_num = line_num self._inputs = [] self._outputs =",
"self._success @property def error_message(self): return self._error_message @property def processor(self): return self._processor def add_input(self,",
"have been invalidated :return: \"\"\" self._start = None self._end = None self.log_stdout =",
"time class Process: \"\"\" Class wrapping a process. A process has some input",
"info (all the properties set by function run()) from another process :param process:",
"language specificities \"\"\" def __init__(self, processor, filename, line_num): self._start = None self._end =",
"set by function run()) because the resources produced by this process have been",
"processor that handle the language specificities \"\"\" def __init__(self, processor, filename, line_num): self._start",
"= error_msg def missing_outputs(self): \"\"\" :return: True if all input resources for this",
"def static_check(self): \"\"\" Runs a verification that the process won't obviously fail. This",
"None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start",
"self.log_stdout = None self.log_stderr = None self._reserved_path = None self._success = None self._error_message",
"res def has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource): return resource in",
"set by function run()) from another process :param process: :return: \"\"\" self._start =",
"if self.has_input(output_resource): return True return False def pick_an_output(self): if not self.has_outputs(): return None",
"self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not None self._reserved_path =",
"@property def code(self): return self._code # TODO Use a setter ? def set_code(self,",
"None self._processor = processor self._filename = filename self._line_num = line_num self._inputs = []",
"Class wrapping a process. A process has some input resources, some output resources,",
"= None self.log_stdout = None self.log_stderr = None self._success = None def static_check(self):",
"\"\"\" Reset the execution info (all the properties set by function run()) because",
"process: :return: \"\"\" self._start = process.start self._end = process.end self._success = process.success self.log_stdout",
"def set_code(self, code): self._code = code @property def success(self): return self._success @property def",
"return self._end @property def id(self): return self._id @property def code(self): return self._code #",
"is used for static analysis before any process is run \"\"\" self._processor.static_check(self) def",
"\"\"\" Returns True if self deprends on a resource created by process\"\"\" for",
"return resource in self._inputs def input_urls(self): return {resource.url for resource in self._inputs} def",
"input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield",
"TODO Use a setter ? def set_code(self, code): self._code = code @property def",
"output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return False def pick_an_output(self): if not",
"code that produces outputs from inputs, a processor that handle the language specificities",
"reset_execution_info(self): \"\"\" Reset the execution info (all the properties set by function run())",
"self._start = process.start self._end = process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr",
"= success self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True if all input",
"created by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return False",
"Runs a verification that the process won't obviously fail. This is used for",
"for static analysis before any process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path,",
"success self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True if all input resources",
"= None self._end = None self.log_stdout = None self.log_stderr = None self._success =",
"return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution info (all",
"res in self._inputs: yield res def iter_outputs(self): for res in self._outputs: yield res",
"self._inputs} def output_urls(self): return {resource.url for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls =",
"Returns True if self deprends on a resource created by process\"\"\" for output_resource",
"[] self._outputs = [] self._code = \"\" self.log_stdout = None self.log_stderr = None",
"self._start = time() def set_end(self, success, error_msg): self._end = time() self._success = success",
"self._reserved_path = None self._success = None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num)",
"all input resources for this process exist, False otherwise \"\"\" result = []",
"@property def error_message(self): return self._error_message @property def processor(self): return self._processor def add_input(self, input_res):",
"return self._error_message @property def processor(self): return self._processor def add_input(self, input_res): self._inputs.append(input_res) def add_output(self,",
"yield res def iter_outputs(self): for res in self._outputs: yield res def has_outputs(self): return",
"static analysis before any process is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout,",
"success(self): return self._success @property def error_message(self): return self._error_message @property def processor(self): return self._processor",
"id(self): return self._id @property def code(self): return self._code # TODO Use a setter",
"None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def set_start(self): self._start",
"from time import time class Process: \"\"\" Class wrapping a process. A process",
"\"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not None self._reserved_path",
"on a resource created by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return",
"self._outputs = [] self._code = \"\" self.log_stdout = None self.log_stderr = None self._reserved_path",
"has some input resources, some output resources, some code that produces outputs from",
"invalidated :return: \"\"\" self._start = None self._end = None self.log_stdout = None self.log_stderr",
"code(self): return self._code # TODO Use a setter ? def set_code(self, code): self._code",
"output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield res def iter_outputs(self): for",
"self._success = None def static_check(self): \"\"\" Runs a verification that the process won't",
"Process: \"\"\" Class wrapping a process. A process has some input resources, some",
"that produces outputs from inputs, a processor that handle the language specificities \"\"\"",
"def retrieve_execution_info(self, process): \"\"\" Copy the execution info (all the properties set by",
"def add_input(self, input_res): self._inputs.append(input_res) def add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in",
"process.start self._end = process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr",
"filename, line_num): self._start = None self._end = None self._processor = processor self._filename =",
"for resource in self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()])",
"process exist, False otherwise \"\"\" result = [] for resource in self.iter_outputs(): if",
"<reponame>lexman/tuttle # -*- coding: utf8 -*- from time import time class Process: \"\"\"",
"handle the language specificities \"\"\" def __init__(self, processor, filename, line_num): self._start = None",
"function run()) because the resources produced by this process have been invalidated :return:",
"input resources, some output resources, some code that produces outputs from inputs, a",
"add_output(self, output): self._outputs.append(output) def iter_inputs(self): for res in self._inputs: yield res def iter_outputs(self):",
"retrieve_execution_info(self, process): \"\"\" Copy the execution info (all the properties set by function",
"[] self._code = \"\" self.log_stdout = None self.log_stderr = None self._reserved_path = None",
"-*- coding: utf8 -*- from time import time class Process: \"\"\" Class wrapping",
"resource in self._inputs def input_urls(self): return {resource.url for resource in self._inputs} def output_urls(self):",
"def start(self): return self._start @property def end(self): return self._end @property def id(self): return",
"-*- from time import time class Process: \"\"\" Class wrapping a process. A",
"self.log_stdout = None self.log_stderr = None self._success = None def static_check(self): \"\"\" Runs",
"= None self.log_stderr = None self._success = None def static_check(self): \"\"\" Runs a",
"if all input resources for this process exist, False otherwise \"\"\" result =",
"None self._reserved_path = None self._success = None self._error_message = None self._id = \"{}_{}\".format(self._filename,",
"self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset",
"set_end(self, success, error_msg): self._end = time() self._success = success self._error_message = error_msg def",
"= process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the",
"line_num): self._start = None self._end = None self._processor = processor self._filename = filename",
"def has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource): return resource in self._inputs",
"by function run()) from another process :param process: :return: \"\"\" self._start = process.start",
"self._start @property def end(self): return self._end @property def id(self): return self._id @property def",
"Reset the execution info (all the properties set by function run()) because the",
"process): \"\"\" Returns True if self deprends on a resource created by process\"\"\"",
"process have been invalidated :return: \"\"\" self._start = None self._end = None self.log_stdout",
"self.log_stderr = log_stderr def set_start(self): self._start = time() def set_end(self, success, error_msg): self._end",
"= None self.log_stderr = None self._reserved_path = None self._success = None self._error_message =",
"= filename self._line_num = line_num self._inputs = [] self._outputs = [] self._code =",
"self._outputs} def sorted_inputs_string(self): sorted_inputs_urls = sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def",
"by this process have been invalidated :return: \"\"\" self._start = None self._end =",
"self._inputs def input_urls(self): return {resource.url for resource in self._inputs} def output_urls(self): return {resource.url",
"False otherwise \"\"\" result = [] for resource in self.iter_outputs(): if not resource.exists():",
"log_stderr def set_start(self): self._start = time() def set_end(self, success, error_msg): self._end = time()",
"iter_outputs(self): for res in self._outputs: yield res def has_outputs(self): return len(self._outputs) > 0",
"self._end @property def id(self): return self._id @property def code(self): return self._code # TODO",
"@property def end(self): return self._end @property def id(self): return self._id @property def code(self):",
"self._code # TODO Use a setter ? def set_code(self, code): self._code = code",
"None self._success = None self._error_message = None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def",
"for this process exist, False otherwise \"\"\" result = [] for resource in",
"coding: utf8 -*- from time import time class Process: \"\"\" Class wrapping a",
"run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not None",
"the execution info (all the properties set by function run()) from another process",
"reserved_path is not None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr",
"time import time class Process: \"\"\" Class wrapping a process. A process has",
"is not None self._reserved_path = reserved_path self.log_stdout = log_stdout self.log_stderr = log_stderr def",
"= None self._id = \"{}_{}\".format(self._filename, self._line_num) @property def start(self): return self._start @property def",
"def iter_inputs(self): for res in self._inputs: yield res def iter_outputs(self): for res in",
"properties set by function run()) because the resources produced by this process have",
"\"\"\" Copy the execution info (all the properties set by function run()) from",
"\"\"\" :return: True if all input resources for this process exist, False otherwise",
"= process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info (all",
"True if self deprends on a resource created by process\"\"\" for output_resource in",
"is run \"\"\" self._processor.static_check(self) def assign_paths(self, reserved_path, log_stdout, log_stderr): assert reserved_path is not",
"self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True if all input resources for",
"a processor that handle the language specificities \"\"\" def __init__(self, processor, filename, line_num):",
"used for static analysis before any process is run \"\"\" self._processor.static_check(self) def assign_paths(self,",
"= line_num self._inputs = [] self._outputs = [] self._code = \"\" self.log_stdout =",
"self._end = process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path",
"self._inputs = [] self._outputs = [] self._code = \"\" self.log_stdout = None self.log_stderr",
"process.end self._success = process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path",
"some code that produces outputs from inputs, a processor that handle the language",
"= time() self._success = success self._error_message = error_msg def missing_outputs(self): \"\"\" :return: True",
"resource created by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource): return True return",
"sorted([resource.url for resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True",
"process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self): \"\"\"",
"filename self._line_num = line_num self._inputs = [] self._outputs = [] self._code = \"\"",
"function run()) from another process :param process: :return: \"\"\" self._start = process.start self._end",
"True if all input resources for this process exist, False otherwise \"\"\" result",
"info (all the properties set by function run()) because the resources produced by",
"set_code(self, code): self._code = code @property def success(self): return self._success @property def error_message(self):",
"for res in self._outputs: yield res def has_outputs(self): return len(self._outputs) > 0 def",
"a setter ? def set_code(self, code): self._code = code @property def success(self): return",
"deprends on a resource created by process\"\"\" for output_resource in process.iter_outputs(): if self.has_input(output_resource):",
"@property def start(self): return self._start @property def end(self): return self._end @property def id(self):",
"return True return False def pick_an_output(self): if not self.has_outputs(): return None return self._outputs[0]",
"error_msg): self._end = time() self._success = success self._error_message = error_msg def missing_outputs(self): \"\"\"",
"not self.has_outputs(): return None return self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution",
"A process has some input resources, some output resources, some code that produces",
"if self deprends on a resource created by process\"\"\" for output_resource in process.iter_outputs():",
"process._reserved_path def reset_execution_info(self): \"\"\" Reset the execution info (all the properties set by",
"line_num self._inputs = [] self._outputs = [] self._code = \"\" self.log_stdout = None",
"resource in self.iter_inputs()]) return \",\".join(sorted_inputs_urls) def depends_on_process(self, process): \"\"\" Returns True if self",
"= process.success self.log_stdout = process.log_stdout self.log_stderr = process.log_stderr self._reserved_path = process._reserved_path def reset_execution_info(self):",
"self._outputs: yield res def has_outputs(self): return len(self._outputs) > 0 def has_input(self, resource): return",
"this process have been invalidated :return: \"\"\" self._start = None self._end = None",
"self.log_stderr = None self._success = None def static_check(self): \"\"\" Runs a verification that",
"= log_stderr def set_start(self): self._start = time() def set_end(self, success, error_msg): self._end =",
"self._outputs[0] def retrieve_execution_info(self, process): \"\"\" Copy the execution info (all the properties set"
] |
[] |
[
"recorded,\\ stopping climate monitor\") SystemExit() # Record climate information in database and send",
"not already been sent today def __checkAndNotify(self, temperature, humidity): # If outside of",
"sould be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if temperature is",
"message += \" temperature is too low,\" if temperature > self.__maxTemp: message +=",
"self.__connectToDatabase(databaseName) # Connects to climate database if it exists, otherwise creating one def",
"self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) #",
"sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\",",
"python3 import requests import json import sqlite3 import sense_hat import time from pushbullet_api",
"'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check if notification sould be sent",
"MonitorNotifier: def __init__(self, databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat() #",
"open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"])",
"'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification has already been sent, return",
"float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\") SystemExit() #",
"monitor class monitor = MonitorNotifier(databaseName) # Check and record climate conditions every minute",
"= cursor.fetchone()[0] # If a notification has already been sent, return immediately if",
"import requests import json import sqlite3 import sense_hat import time from pushbullet_api import",
"temperature > self.__maxTemp or\\ humidity < self.__minHumid or humidity > self.__maxHumid: # Check",
"import ClimateUtil # Monitor and notification class class MonitorNotifier: def __init__(self, databaseName): #",
"range, check database if notification # has already been sent today if temperature",
"IF NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create",
"check database if notification # has already been sent today if temperature <",
"\".\" # Wait until program is able to connect to internet while not",
"= float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to",
"access self.__sense = sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\", \"r\") as",
"float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() #",
"doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit",
"humidity < self.__minHumid or humidity > self.__maxHumid: # Check if notification has already",
"TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating of table",
"Database name variable databaseName = \"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName)",
"is too low,\" if temperature > self.__maxTemp: message += \" temperature is too",
"while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending",
"exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating",
"or temperature > self.__maxTemp or\\ humidity < self.__minHumid or humidity > self.__maxHumid: #",
"self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor for database cursor = self.__database.cursor()",
"self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now',",
"notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now',",
"# If outside of config range, check database if notification # has already",
"climate alert\" message = \"Warning,\" if temperature < self.__minTemp: message += \" temperature",
"low,\" if humidity > self.__maxHumid: message += \" humidity is too high,\" message",
"message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with self.__database: cursor = self.__database.cursor()",
"data recorded,\\ stopping climate monitor\") SystemExit() # Record climate information in database and",
"\" temperature is too low,\" if temperature > self.__maxTemp: message += \" temperature",
"databaseName = \"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName) # Check and",
"too low,\" if temperature > self.__maxTemp: message += \" temperature is too high,\"",
"self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI =",
"to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) #",
"database and send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time,",
"Get and validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity())",
"self.__maxTemp or\\ humidity < self.__minHumid or humidity > self.__maxHumid: # Check if notification",
"internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record",
"self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API",
"of table self.__database.commit() # Record the current temp data into database def recordClimate(self):",
"into database def recordClimate(self): # Get and validate current climate information try: temperature",
"validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError:",
"notification if temperature is out of range # and a notification has not",
"has not already been sent today def __checkAndNotify(self, temperature, humidity): # If outside",
"it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\") #",
"1: return # Construct pushbullet message strings title = \"Raspberry Pi climate alert\"",
"self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT",
"monitor = MonitorNotifier(databaseName) # Check and record climate conditions every minute while True:",
"sense_hat import time from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil # Monitor",
"humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check if",
"today def __checkAndNotify(self, temperature, humidity): # If outside of config range, check database",
"(DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__ == \"__main__\": # Database name",
"> self.__maxTemp: message += \" temperature is too high,\" if humidity < self.__minHumid:",
"EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification table",
"database file self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor for database cursor",
"# Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables",
"requests import json import sqlite3 import sense_hat import time from pushbullet_api import PushbulletAPI",
"\\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount",
"cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() #",
"jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"])",
"self.__database.cursor() # Create climate data table if it doesn't exist cursor.execute(\"CREATE TABLE IF",
"import sqlite3 import sense_hat import time from pushbullet_api import PushbulletAPI from climate_util import",
"#!/usr/bin/env python3 import requests import json import sqlite3 import sense_hat import time from",
"message += \" humidity is too low,\" if humidity > self.__maxHumid: message +=",
"if notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if",
"humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\")",
"# Load JSON config variables with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile)",
"self.__minHumid or humidity > self.__maxHumid: # Check if notification has already been sent",
"current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning:",
"DATETIME)\") # Commit creating of table self.__database.commit() # Record the current temp data",
"sent, return immediately if recordCount >= 1: return # Construct pushbullet message strings",
"\" humidity is too high,\" message = message.rstrip(',') + \".\" # Wait until",
"# Connects to climate database if it exists, otherwise creating one def __connectToDatabase(self,",
"not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of",
"strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a",
"database cursor = self.__database.cursor() # Create climate data table if it doesn't exist",
"is able to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet",
"file self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor for database cursor =",
"PushbulletAPI() # Connect to database for logging climate data self.__connectToDatabase(databaseName) # Connects to",
"strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification has already been",
"out of range # and a notification has not already been sent today",
"\" temperature is too high,\" if humidity < self.__minHumid: message += \" humidity",
"JSON config variables with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp =",
"been sent, return immediately if recordCount >= 1: return # Construct pushbullet message",
"Get cursor for database cursor = self.__database.cursor() # Create climate data table if",
"with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\")",
"Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with self.__database: cursor",
"cursor for database cursor = self.__database.cursor() # Create climate data table if it",
"temperature is out of range # and a notification has not already been",
"# Sends a pushbullet notification if temperature is out of range # and",
"humidity) # Sends a pushbullet notification if temperature is out of range #",
"with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp =",
"# Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with self.__database:",
"(timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__ == \"__main__\":",
"notification class class MonitorNotifier: def __init__(self, databaseName): # Get sense hat access self.__sense",
"if humidity < self.__minHumid: message += \" humidity is too low,\" if humidity",
"= json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid =",
"\\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification table if it",
"> self.__maxTemp or\\ humidity < self.__minHumid or humidity > self.__maxHumid: # Check if",
"If a notification has already been sent, return immediately if recordCount >= 1:",
"float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet",
"NUMERIC)\") # Create notification table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT",
"ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit()",
"Monitor and notification class class MonitorNotifier: def __init__(self, databaseName): # Get sense hat",
"Commit creating of table self.__database.commit() # Record the current temp data into database",
"self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if temperature is out of range",
"config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid",
"# and a notification has not already been sent today def __checkAndNotify(self, temperature,",
"NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating of table self.__database.commit() #",
"Pi climate alert\" message = \"Warning,\" if temperature < self.__minTemp: message += \"",
"data into database def recordClimate(self): # Get and validate current climate information try:",
"it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time DATETIME, temperature",
"Load JSON config variables with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp",
"otherwise creating one def __connectToDatabase(self, databaseName): # Connect to database file self.__database =",
"# Connect to database for logging climate data self.__connectToDatabase(databaseName) # Connects to climate",
"Record the current temp data into database def recordClimate(self): # Get and validate",
"\\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification has",
"+= \" humidity is too low,\" if humidity > self.__maxHumid: message += \"",
"== \"__main__\": # Database name variable databaseName = \"climate_data.db\" # Initialize monitor class",
"time from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil # Monitor and notification",
"Check if notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification",
"connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message)",
"table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent",
"__checkAndNotify(self, temperature, humidity): # If outside of config range, check database if notification",
"doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC,",
"high,\" if humidity < self.__minHumid: message += \" humidity is too low,\" if",
"\\ (timesent DATETIME)\") # Commit creating of table self.__database.commit() # Record the current",
"DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification table if it doesn't exist",
"Check if notification has already been sent today with self.__database: cursor = self.__database.cursor()",
"cursor = self.__database.cursor() # Create climate data table if it doesn't exist cursor.execute(\"CREATE",
"\"__main__\": # Database name variable databaseName = \"climate_data.db\" # Initialize monitor class monitor",
"has already been sent today if temperature < self.__minTemp or temperature > self.__maxTemp",
"if __name__ == \"__main__\": # Database name variable databaseName = \"climate_data.db\" # Initialize",
"= \"Raspberry Pi climate alert\" message = \"Warning,\" if temperature < self.__minTemp: message",
"self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y',",
"if notification has already been sent today with self.__database: cursor = self.__database.cursor() cursor.execute(",
"# Commit creating of table self.__database.commit() # Record the current temp data into",
"current temp data into database def recordClimate(self): # Get and validate current climate",
"?, ?)\", (temperature, humidity)) self.__database.commit() # Check if notification sould be sent self.__checkAndNotify(temperature,",
"humidity > self.__maxHumid: message += \" humidity is too high,\" message = message.rstrip(',')",
"it exists, otherwise creating one def __connectToDatabase(self, databaseName): # Connect to database file",
"\"Raspberry Pi climate alert\" message = \"Warning,\" if temperature < self.__minTemp: message +=",
"is too high,\" if humidity < self.__minHumid: message += \" humidity is too",
"in database and send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData",
"for database cursor = self.__database.cursor() # Create climate data table if it doesn't",
"databaseName): # Connect to database file self.__database = sqlite3.connect(databaseName) with self.__database: # Get",
"sent today if temperature < self.__minTemp or temperature > self.__maxTemp or\\ humidity <",
"climate data self.__connectToDatabase(databaseName) # Connects to climate database if it exists, otherwise creating",
"database for logging climate data self.__connectToDatabase(databaseName) # Connects to climate database if it",
"float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate",
"# Create notification table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS",
"\\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__ == \"__main__\": #",
"config range, check database if notification # has already been sent today if",
"a pushbullet notification if temperature is out of range # and a notification",
"today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\",
"if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time DATETIME,",
"range # and a notification has not already been sent today def __checkAndNotify(self,",
"recordClimate(self): # Get and validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity",
"MonitorNotifier(databaseName) # Check and record climate conditions every minute while True: monitor.recordClimate() time.sleep(60)",
"ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification",
"self.__database.commit() # Record the current temp data into database def recordClimate(self): # Get",
"cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y',",
"humidity)) self.__database.commit() # Check if notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends",
"# Check if notification has already been sent today with self.__database: cursor =",
"humidity is too low,\" if humidity > self.__maxHumid: message += \" humidity is",
"Sends a pushbullet notification if temperature is out of range # and a",
"name variable databaseName = \"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName) #",
"self.__minTemp or temperature > self.__maxTemp or\\ humidity < self.__minHumid or humidity > self.__maxHumid:",
"+= \" humidity is too high,\" message = message.rstrip(',') + \".\" # Wait",
"Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables with",
"self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect",
"+= \" temperature is too high,\" if humidity < self.__minHumid: message += \"",
"to database for logging climate data self.__connectToDatabase(databaseName) # Connects to climate database if",
"climate monitor\") SystemExit() # Record climate information in database and send notification with",
"creating of table self.__database.commit() # Record the current temp data into database def",
"self.__maxTemp: message += \" temperature is too high,\" if humidity < self.__minHumid: message",
"\\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] #",
"# Database name variable databaseName = \"climate_data.db\" # Initialize monitor class monitor =",
"temperature > self.__maxTemp: message += \" temperature is too high,\" if humidity <",
"send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity)",
"for logging climate data self.__connectToDatabase(databaseName) # Connects to climate database if it exists,",
"Initialize monitor class monitor = MonitorNotifier(databaseName) # Check and record climate conditions every",
"to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title,",
"\" humidity is too low,\" if humidity > self.__maxHumid: message += \" humidity",
"database def recordClimate(self): # Get and validate current climate information try: temperature =",
"VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check if notification sould",
"= \"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName) # Check and record",
"class class MonitorNotifier: def __init__(self, databaseName): # Get sense hat access self.__sense =",
"FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount =",
"pushbullet notification if temperature is out of range # and a notification has",
"and notification class class MonitorNotifier: def __init__(self, databaseName): # Get sense hat access",
"float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to database",
"has already been sent, return immediately if recordCount >= 1: return # Construct",
"cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature,",
"recordCount >= 1: return # Construct pushbullet message strings title = \"Raspberry Pi",
"If outside of config range, check database if notification # has already been",
"message += \" humidity is too high,\" message = message.rstrip(',') + \".\" #",
"(DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check if notification sould be",
"if temperature is out of range # and a notification has not already",
"program is able to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send",
"(time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification table if it doesn't",
"config variables with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"])",
"NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification",
"information in database and send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO",
"__connectToDatabase(self, databaseName): # Connect to database file self.__database = sqlite3.connect(databaseName) with self.__database: #",
"# Record climate information in database and send notification with self.__database: cursor =",
"\"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now',",
"# Monitor and notification class class MonitorNotifier: def __init__(self, databaseName): # Get sense",
"< self.__minTemp or temperature > self.__maxTemp or\\ humidity < self.__minHumid or humidity >",
"import sense_hat import time from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil #",
"self.__maxHumid: message += \" humidity is too high,\" message = message.rstrip(',') + \".\"",
"ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") # Create notification table if",
"of range # and a notification has not already been sent today def",
"import json import sqlite3 import sense_hat import time from pushbullet_api import PushbulletAPI from",
"Record sending of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent)",
"\"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid",
"if humidity > self.__maxHumid: message += \" humidity is too high,\" message =",
"with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES",
"table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time",
"to climate database if it exists, otherwise creating one def __connectToDatabase(self, databaseName): #",
"Connect to database file self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor for",
"with self.__database: # Get cursor for database cursor = self.__database.cursor() # Create climate",
"(time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() #",
"WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If",
"is too low,\" if humidity > self.__maxHumid: message += \" humidity is too",
"until program is able to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) #",
"json import sqlite3 import sense_hat import time from pushbullet_api import PushbulletAPI from climate_util",
"# Construct pushbullet message strings title = \"Raspberry Pi climate alert\" message =",
"too low,\" if humidity > self.__maxHumid: message += \" humidity is too high,\"",
"self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ =",
"from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil # Monitor and notification class",
"# Get cursor for database cursor = self.__database.cursor() # Create climate data table",
"and send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature,",
"Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__ ==",
"or humidity > self.__maxHumid: # Check if notification has already been sent today",
"cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\")",
"creating one def __connectToDatabase(self, databaseName): # Connect to database file self.__database = sqlite3.connect(databaseName)",
"= float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping",
"Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0]",
"Create notification table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications",
"= float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\") SystemExit()",
"pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with self.__database: cursor =",
"or\\ humidity < self.__minHumid or humidity > self.__maxHumid: # Check if notification has",
"notification table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\",
"timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification",
"immediately if recordCount >= 1: return # Construct pushbullet message strings title =",
"climate data table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData",
"already been sent, return immediately if recordCount >= 1: return # Construct pushbullet",
"import PushbulletAPI from climate_util import ClimateUtil # Monitor and notification class class MonitorNotifier:",
"a notification has already been sent, return immediately if recordCount >= 1: return",
"sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if temperature is out of",
"pushbullet message strings title = \"Raspberry Pi climate alert\" message = \"Warning,\" if",
"been sent today if temperature < self.__minTemp or temperature > self.__maxTemp or\\ humidity",
"has already been sent today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*)",
"been sent today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM",
"self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging climate data self.__connectToDatabase(databaseName) #",
"# Check if notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet",
"data self.__connectToDatabase(databaseName) # Connects to climate database if it exists, otherwise creating one",
"= PushbulletAPI() # Connect to database for logging climate data self.__connectToDatabase(databaseName) # Connects",
"= float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI()",
"\"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName) # Check and record climate",
"self.__minTemp: message += \" temperature is too low,\" if temperature > self.__maxTemp: message",
"climate data recorded,\\ stopping climate monitor\") SystemExit() # Record climate information in database",
"hat access self.__sense = sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\", \"r\")",
"sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\", \"r\") as jsonFile: config =",
"= message.rstrip(',') + \".\" # Wait until program is able to connect to",
"already been sent today if temperature < self.__minTemp or temperature > self.__maxTemp or\\",
"= sqlite3.connect(databaseName) with self.__database: # Get cursor for database cursor = self.__database.cursor() #",
"Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging climate",
"too high,\" message = message.rstrip(',') + \".\" # Wait until program is able",
"exists, otherwise creating one def __connectToDatabase(self, databaseName): # Connect to database file self.__database",
"humidity NUMERIC)\") # Create notification table if it doesn't exist cursor.execute(\"CREATE TABLE IF",
"if temperature > self.__maxTemp: message += \" temperature is too high,\" if humidity",
"= self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?,",
"humidity < self.__minHumid: message += \" humidity is too low,\" if humidity >",
"= self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main",
"import time from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil # Monitor and",
"and validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except",
"\"Warning,\" if temperature < self.__minTemp: message += \" temperature is too low,\" if",
"variables with open(\"config.json\", \"r\") as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp",
"temperature NUMERIC, humidity NUMERIC)\") # Create notification table if it doesn't exist cursor.execute(\"CREATE",
"data table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\",
"# has already been sent today if temperature < self.__minTemp or temperature >",
"Construct pushbullet message strings title = \"Raspberry Pi climate alert\" message = \"Warning,\"",
"class MonitorNotifier: def __init__(self, databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat()",
"from climate_util import ClimateUtil # Monitor and notification class class MonitorNotifier: def __init__(self,",
"database if notification # has already been sent today if temperature < self.__minTemp",
"= strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification has already",
"monitor\") SystemExit() # Record climate information in database and send notification with self.__database:",
"sent today def __checkAndNotify(self, temperature, humidity): # If outside of config range, check",
"COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\ = strftime('%d-%m-%Y', DATETIME('now', 'localtime'))\")",
"logging climate data self.__connectToDatabase(databaseName) # Connects to climate database if it exists, otherwise",
"ClimateUtil # Monitor and notification class class MonitorNotifier: def __init__(self, databaseName): # Get",
"climate information in database and send notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT",
"strings title = \"Raspberry Pi climate alert\" message = \"Warning,\" if temperature <",
"too high,\" if humidity < self.__minHumid: message += \" humidity is too low,\"",
"NUMERIC, humidity NUMERIC)\") # Create notification table if it doesn't exist cursor.execute(\"CREATE TABLE",
"Record climate information in database and send notification with self.__database: cursor = self.__database.cursor()",
"< self.__minTemp: message += \" temperature is too low,\" if temperature > self.__maxTemp:",
"is out of range # and a notification has not already been sent",
"= float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access",
"to database file self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor for database",
"if temperature < self.__minTemp or temperature > self.__maxTemp or\\ humidity < self.__minHumid or",
"and a notification has not already been sent today def __checkAndNotify(self, temperature, humidity):",
"notification # has already been sent today if temperature < self.__minTemp or temperature",
"if temperature < self.__minTemp: message += \" temperature is too low,\" if temperature",
"> self.__maxHumid: message += \" humidity is too high,\" message = message.rstrip(',') +",
"as jsonFile: config = json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid =",
"cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'),",
"= float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load",
"climate database if it exists, otherwise creating one def __connectToDatabase(self, databaseName): # Connect",
"self.__database.commit() # Check if notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends a",
"def __init__(self, databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat() # Load",
"__name__ == \"__main__\": # Database name variable databaseName = \"climate_data.db\" # Initialize monitor",
"be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if temperature is out",
"> self.__maxHumid: # Check if notification has already been sent today with self.__database:",
"Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging",
"= \"Warning,\" if temperature < self.__minTemp: message += \" temperature is too low,\"",
"self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit()",
"# Initialize monitor class monitor = MonitorNotifier(databaseName) # Check and record climate conditions",
"temp data into database def recordClimate(self): # Get and validate current climate information",
"notification sould be sent self.__checkAndNotify(temperature, humidity) # Sends a pushbullet notification if temperature",
"able to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1) # Send pushbullet message",
"try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data",
"def __connectToDatabase(self, databaseName): # Connect to database file self.__database = sqlite3.connect(databaseName) with self.__database:",
"except ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\") SystemExit() # Record",
"VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__ == \"__main__\": # Database",
"today if temperature < self.__minTemp or temperature > self.__maxTemp or\\ humidity < self.__minHumid",
"sending of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\",
"'localtime'))\") self.__database.commit() # Main method if __name__ == \"__main__\": # Database name variable",
"return immediately if recordCount >= 1: return # Construct pushbullet message strings title",
"?)\", (temperature, humidity)) self.__database.commit() # Check if notification sould be sent self.__checkAndNotify(temperature, humidity)",
"one def __connectToDatabase(self, databaseName): # Connect to database file self.__database = sqlite3.connect(databaseName) with",
"exist cursor.execute(\"CREATE TABLE IF NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity",
"the current temp data into database def recordClimate(self): # Get and validate current",
"with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE",
"sent today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications",
"# Create climate data table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT",
"table self.__database.commit() # Record the current temp data into database def recordClimate(self): #",
"Connects to climate database if it exists, otherwise creating one def __connectToDatabase(self, databaseName):",
"PushbulletAPI from climate_util import ClimateUtil # Monitor and notification class class MonitorNotifier: def",
"self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\",",
"cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if",
"temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check",
"notification has already been sent, return immediately if recordCount >= 1: return #",
"low,\" if temperature > self.__maxTemp: message += \" temperature is too high,\" if",
"message.rstrip(',') + \".\" # Wait until program is able to connect to internet",
"TABLE IF NOT EXISTS ClimateData \\ (time DATETIME, temperature NUMERIC, humidity NUMERIC)\") #",
"temperature < self.__minTemp: message += \" temperature is too low,\" if temperature >",
"temperature < self.__minTemp or temperature > self.__maxTemp or\\ humidity < self.__minHumid or humidity",
"Invalid climate data recorded,\\ stopping climate monitor\") SystemExit() # Record climate information in",
"method if __name__ == \"__main__\": # Database name variable databaseName = \"climate_data.db\" #",
"high,\" message = message.rstrip(',') + \".\" # Wait until program is able to",
"def __checkAndNotify(self, temperature, humidity): # If outside of config range, check database if",
"INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method if __name__",
"pushbullet_api import PushbulletAPI from climate_util import ClimateUtil # Monitor and notification class class",
"class monitor = MonitorNotifier(databaseName) # Check and record climate conditions every minute while",
"a notification has not already been sent today def __checkAndNotify(self, temperature, humidity): #",
"< self.__minHumid: message += \" humidity is too low,\" if humidity > self.__maxHumid:",
"already been sent today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\",
"humidity is too high,\" message = message.rstrip(',') + \".\" # Wait until program",
"is too high,\" message = message.rstrip(',') + \".\" # Wait until program is",
"title = \"Raspberry Pi climate alert\" message = \"Warning,\" if temperature < self.__minTemp:",
"notification has not already been sent today def __checkAndNotify(self, temperature, humidity): # If",
"self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES (DATETIME('now', 'localtime'))\") self.__database.commit() # Main method",
"# If a notification has already been sent, return immediately if recordCount >=",
"= self.__database.cursor() # Create climate data table if it doesn't exist cursor.execute(\"CREATE TABLE",
"= sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\", \"r\") as jsonFile: config",
"message strings title = \"Raspberry Pi climate alert\" message = \"Warning,\" if temperature",
"self.__maxHumid: # Check if notification has already been sent today with self.__database: cursor",
"= MonitorNotifier(databaseName) # Check and record climate conditions every minute while True: monitor.recordClimate()",
"+= \" temperature is too low,\" if temperature > self.__maxTemp: message += \"",
"database if it exists, otherwise creating one def __connectToDatabase(self, databaseName): # Connect to",
"(temperature, humidity)) self.__database.commit() # Check if notification sould be sent self.__checkAndNotify(temperature, humidity) #",
"already been sent today def __checkAndNotify(self, temperature, humidity): # If outside of config",
"= self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent) \\",
"of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications (timesent) \\ VALUES",
"# Wait until program is able to connect to internet while not ClimateUtil.checkConnection():",
"EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating of table self.__database.commit() # Record",
"# Main method if __name__ == \"__main__\": # Database name variable databaseName =",
"cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating of",
"print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\") SystemExit() # Record climate information",
"notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO ClimateData (time, temperature, humidity) \\",
"def recordClimate(self): # Get and validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense))",
"stopping climate monitor\") SystemExit() # Record climate information in database and send notification",
"sqlite3.connect(databaseName) with self.__database: # Get cursor for database cursor = self.__database.cursor() # Create",
"temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate data recorded,\\",
"alert\" message = \"Warning,\" if temperature < self.__minTemp: message += \" temperature is",
"Notifications \\ (timesent DATETIME)\") # Commit creating of table self.__database.commit() # Record the",
"been sent today def __checkAndNotify(self, temperature, humidity): # If outside of config range,",
"Create climate data table if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS",
"API access self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging climate data",
"access self.__pushbulletAPI = PushbulletAPI() # Connect to database for logging climate data self.__connectToDatabase(databaseName)",
"if it exists, otherwise creating one def __connectToDatabase(self, databaseName): # Connect to database",
"\\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity)) self.__database.commit() # Check if notification",
"time.sleep(1) # Send pushbullet message self.__pushbulletAPI.sendNotification(title, message) # Record sending of notification with",
"self.__database.commit() # Main method if __name__ == \"__main__\": # Database name variable databaseName",
"cursor = self.__database.cursor() cursor.execute( \"SELECT COUNT(*) \\ FROM Notifications \\ WHERE strftime('%d-%m-%Y', timesent)",
"cursor.fetchone()[0] # If a notification has already been sent, return immediately if recordCount",
"< self.__minHumid or humidity > self.__maxHumid: # Check if notification has already been",
"# Get and validate current climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity =",
"# Load Pushbullet API access self.__pushbulletAPI = PushbulletAPI() # Connect to database for",
"if notification # has already been sent today if temperature < self.__minTemp or",
"if it doesn't exist cursor.execute(\"CREATE TABLE IF NOT EXISTS Notifications \\ (timesent DATETIME)\")",
"humidity): # If outside of config range, check database if notification # has",
"__init__(self, databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON",
"INTO ClimateData (time, temperature, humidity) \\ VALUES (DATETIME('now', 'localtime'), ?, ?)\", (temperature, humidity))",
"+ \".\" # Wait until program is able to connect to internet while",
"message) # Record sending of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO",
"databaseName): # Get sense hat access self.__sense = sense_hat.SenseHat() # Load JSON config",
"Wait until program is able to connect to internet while not ClimateUtil.checkConnection(): time.sleep(1)",
"message = message.rstrip(',') + \".\" # Wait until program is able to connect",
"information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid climate",
"of config range, check database if notification # has already been sent today",
">= 1: return # Construct pushbullet message strings title = \"Raspberry Pi climate",
"Connect to database for logging climate data self.__connectToDatabase(databaseName) # Connects to climate database",
"(timesent DATETIME)\") # Commit creating of table self.__database.commit() # Record the current temp",
"if recordCount >= 1: return # Construct pushbullet message strings title = \"Raspberry",
"# Record sending of notification with self.__database: cursor = self.__database.cursor() cursor.execute(\"INSERT INTO Notifications",
"humidity > self.__maxHumid: # Check if notification has already been sent today with",
"return # Construct pushbullet message strings title = \"Raspberry Pi climate alert\" message",
"message = \"Warning,\" if temperature < self.__minTemp: message += \" temperature is too",
"# Record the current temp data into database def recordClimate(self): # Get and",
"variable databaseName = \"climate_data.db\" # Initialize monitor class monitor = MonitorNotifier(databaseName) # Check",
"Main method if __name__ == \"__main__\": # Database name variable databaseName = \"climate_data.db\"",
"sqlite3 import sense_hat import time from pushbullet_api import PushbulletAPI from climate_util import ClimateUtil",
"outside of config range, check database if notification # has already been sent",
"# Connect to database file self.__database = sqlite3.connect(databaseName) with self.__database: # Get cursor",
"DATETIME('now', 'localtime'))\") recordCount = cursor.fetchone()[0] # If a notification has already been sent,",
"self.__minHumid: message += \" humidity is too low,\" if humidity > self.__maxHumid: message",
"climate information try: temperature = float(ClimateUtil.getCalibratedTemp(self.__sense)) humidity = float(self.__sense.get_humidity()) except ValueError: print(\"Warning: Invalid",
"IF NOT EXISTS Notifications \\ (timesent DATETIME)\") # Commit creating of table self.__database.commit()",
"notification has already been sent today with self.__database: cursor = self.__database.cursor() cursor.execute( \"SELECT",
"SystemExit() # Record climate information in database and send notification with self.__database: cursor",
"self.__sense = sense_hat.SenseHat() # Load JSON config variables with open(\"config.json\", \"r\") as jsonFile:",
"ValueError: print(\"Warning: Invalid climate data recorded,\\ stopping climate monitor\") SystemExit() # Record climate",
"temperature is too high,\" if humidity < self.__minHumid: message += \" humidity is",
"climate_util import ClimateUtil # Monitor and notification class class MonitorNotifier: def __init__(self, databaseName):",
"self.__database: # Get cursor for database cursor = self.__database.cursor() # Create climate data",
"recordCount = cursor.fetchone()[0] # If a notification has already been sent, return immediately",
"json.load(jsonFile) self.__minTemp = float(config[\"min_temperature\"]) self.__maxTemp = float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"])",
"float(config[\"max_temperature\"]) self.__minHumid = float(config[\"min_humidity\"]) self.__maxHumid = float(config[\"max_humidity\"]) # Load Pushbullet API access self.__pushbulletAPI",
"temperature is too low,\" if temperature > self.__maxTemp: message += \" temperature is",
"temperature, humidity): # If outside of config range, check database if notification #",
"message += \" temperature is too high,\" if humidity < self.__minHumid: message +="
] |
[
"Any from flax import linen as nn import jax import jax.numpy as jnp",
"KIND, either express or implied. # See the License for the specific language",
"setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes",
"Unless required by applicable law or agreed to in writing, software # distributed",
"= config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder =",
"Exception IPA-GNN on data with no errors.') else: logits = nn.Dense( features=num_classes, name='output'",
") else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x):",
"from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from",
"spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module):",
"encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if",
"NotImplementedError('Multiple error classes and multiple no-error classes.') assert len(info.error_ids) == 1 error_id =",
"1: # Multiple No-Error classes; only one error class. if len(info.error_ids) > 1:",
"jax.numpy as jnp from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn",
"info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def",
"config = self.config info = self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] #",
"ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer",
"core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any",
"docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens",
"no exception) # logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)(",
"this file except in compliance with the License. # You may obtain a",
"raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1:",
"assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings)",
"tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention:",
"def __call__(self, x): config = self.config info = self.info tokens = x['tokens'] docstring_tokens",
"core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn",
"ANY KIND, either express or implied. # See the License for the specific",
"false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape:",
"if len(info.no_error_ids) == 1: # Multiple error classes; only one No-Error class. no_error_id",
"= config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config,",
"raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info: Any",
"core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn",
"import transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"for the specific language governing permissions and # limitations under the License. \"\"\"IPA-GNN",
"Multiple error classes; only one No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense(",
"and # limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from",
"and multiple no-error classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits =",
"logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9,",
"x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'],",
"classes; only one No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output'",
"max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn =",
"1: raise NotImplementedError('Multiple error classes and multiple no-error classes.') assert len(info.error_ids) == 1",
"Copyright (C) 2021 Google Inc. # # Licensed under the Apache License, Version",
"specific language governing permissions and # limitations under the License. \"\"\"IPA-GNN models.\"\"\" from",
"OF ANY KIND, either express or implied. # See the License for the",
"tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0]",
"docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens,",
"info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config = self.config info =",
"== 1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e",
"core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn",
"transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN(",
"= spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or",
"features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception) # logits.shape: batch_size, num_classes logits",
"(C) 2021 Google Inc. # # Licensed under the Apache License, Version 2.0",
"max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self,",
"edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size",
"P(e | yes exception) # logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits",
"features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception) # logits.shape: batch_size, num_classes logits",
"logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception) # logits.shape:",
"max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size,",
"= encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else:",
"or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config)",
"error classes; only one No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes,",
"else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape: batch_size, num_classes return logits,",
"max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"# limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from flax",
"docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs,",
"IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config =",
"Multiple No-Error classes; only one error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple",
"permissions and # limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any",
"Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size = self.info.vocab_size",
"governing permissions and # limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing import",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"= ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes",
"encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn",
"no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes",
"linen as nn import jax import jax.numpy as jnp from core.data import error_kinds",
"tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes'])",
"under the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from flax import linen",
"len(info.error_ids) == 1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) #",
"# logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer +",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges",
"# exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes",
"exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions",
"= self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges =",
"+ 1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried",
"IPA-GNN on data with no errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings)",
"from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import",
"required by applicable law or agreed to in writing, software # distributed under",
"applicable law or agreed to in writing, software # distributed under the License",
"docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else:",
"= logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits)",
") @nn.compact def __call__(self, x): config = self.config info = self.info tokens =",
"# error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN",
"spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention:",
"from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as",
"as jnp from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import",
"or agreed to in writing, software # distributed under the License is distributed",
"# exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape:",
"2021 Google Inc. # # Licensed under the Apache License, Version 2.0 (the",
"flax import linen as nn import jax import jax.numpy as jnp from core.data",
"core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules",
"max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens,",
"= config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes,",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from",
"P(e | no exception) # logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits",
"docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask)",
"len(info.no_error_ids) == 1: # Multiple error classes; only one No-Error class. no_error_id =",
"# encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens)",
"edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape:",
"no-error classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes,",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception) #",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask(",
"= ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if",
"# ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9,",
"License. # You may obtain a copy of the License at # #",
"docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], )",
"1: # Multiple error classes; only one No-Error class. no_error_id = info.no_error_ids[0] logits",
"x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings",
"self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, )",
"no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size",
"= nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception) # logits.shape: batch_size,",
"ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] #",
"raise ValueError('Tried using Exception IPA-GNN on data with no errors.') else: logits =",
"compliance with the License. # You may obtain a copy of the License",
"jax import jax.numpy as jnp from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn",
"max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape:",
"logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception) # logits.shape:",
"batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask =",
"batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask",
"raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"= encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn",
"max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False,",
"__call__(self, x): config = self.config info = self.info tokens = x['tokens'] docstring_tokens =",
"raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple error",
"the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from flax import linen as",
"= self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film",
"edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size,",
"not use this file except in compliance with the License. # You may",
"start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size",
"on data with no errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) #",
"transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, )",
"error classes and multiple no-error classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0]",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer",
"x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs =",
"> 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size",
"multiple no-error classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits = nn.Dense(",
"info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder",
"or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask =",
"docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings =",
"# you may not use this file except in compliance with the License.",
"config = self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges",
"agreed to in writing, software # distributed under the License is distributed on",
"info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception) #",
"ValueError('Tried using Exception IPA-GNN on data with no errors.') else: logits = nn.Dense(",
"error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on",
"(the \"License\"); # you may not use this file except in compliance with",
"transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens",
"hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens >",
"logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9,",
"= nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder(",
"batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size,",
"| yes exception) # logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits =",
"typing import Any from flax import linen as nn import jax import jax.numpy",
") self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps,",
"ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids)",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"elif len(info.no_error_ids) > 1: # Multiple No-Error classes; only one error class. if",
"num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config,",
"ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'],",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits",
"exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings =",
"Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e |",
"from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config:",
"= compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps,",
"self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or",
"<reponame>google-research/runtime-error-prediction # Copyright (C) 2021 Google Inc. # # Licensed under the Apache",
"file except in compliance with the License. # You may obtain a copy",
"the specific language governing permissions and # limitations under the License. \"\"\"IPA-GNN models.\"\"\"",
"batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape:",
"ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size",
"batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer =",
"no errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape: batch_size, num_classes",
"classes and multiple no-error classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits",
"classes.') assert len(info.error_ids) == 1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output'",
"License for the specific language governing permissions and # limitations under the License.",
"error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and multiple no-error",
"# Multiple error classes; only one No-Error class. no_error_id = info.no_error_ids[0] logits =",
"to in writing, software # distributed under the License is distributed on an",
"config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config = self.config info = self.info",
")(raise_node_embeddings) # P(e | yes exception) # logits.shape: batch_size, num_classes logits = logits.at[:,",
"import jax.numpy as jnp from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from",
"if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] #",
"implied. # See the License for the specific language governing permissions and #",
"from typing import Any from flax import linen as nn import jax import",
"\"License\"); # you may not use this file except in compliance with the",
"error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape:",
"with no errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape: batch_size,",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans",
"else: raise ValueError('Tried using Exception IPA-GNN on data with no errors.') else: logits",
"no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error",
"num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer +",
"# Multiple No-Error classes; only one error class. if len(info.error_ids) > 1: raise",
"using Exception IPA-GNN on data with no errors.') else: logits = nn.Dense( features=num_classes,",
"= config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, )",
"import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from",
"one error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and multiple",
"= docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size,",
"= self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size",
"or implied. # See the License for the specific language governing permissions and",
"logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape: batch_size, num_classes return logits, ipagnn_output",
"config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config",
"ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple error classes; only",
"import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class",
"errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape: batch_size, num_classes return",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] #",
"# ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape:",
"in writing, software # distributed under the License is distributed on an \"AS",
"hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings",
"ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] #",
"= self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'],",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None",
"x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings =",
"1 error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e |",
"x): config = self.config info = self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens']",
"no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error classes; only one error class.",
"exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if",
"import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import",
")(exit_node_embeddings) # P(e | no exception) # logits.shape: batch_size, num_classes logits = logits.at[:,",
"= self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None ipagnn_output =",
"logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error classes; only",
"logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on data with no errors.')",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import",
"you may not use this file except in compliance with the License. #",
"max_steps=max_steps, ) @nn.compact def __call__(self, x): config = self.config info = self.info tokens",
"= self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask,",
"config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if",
"= logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits)",
"def setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes =",
"= info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer =",
"1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1:",
"compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math",
"batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn:",
"= info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception)",
"use this file except in compliance with the License. # You may obtain",
"if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule(",
"vocab_size = self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps",
"# ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings']",
"exception) # logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer",
"transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder(",
"from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from",
"# Copyright (C) 2021 Google Inc. # # Licensed under the Apache License,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from",
"else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config",
"max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config,",
"Google Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"# docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings =",
"name='output' )(raise_node_embeddings) # P(e | yes exception) # logits.shape: batch_size, num_classes logits =",
"nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no exception) # logits.shape: batch_size, num_classes",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9,",
"only one error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and",
"class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and multiple no-error classes.')",
"= None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'],",
"ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes =",
"= logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error classes; only one",
") # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size #",
"logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib from third_party.flax_examples",
"use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size,",
"self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif",
"hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None",
"logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on data with",
"error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size",
"batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings",
"error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on data with no errors.') else:",
") if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder",
"# # Unless required by applicable law or agreed to in writing, software",
"config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config,",
"config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder =",
"hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size,",
"express or implied. # See the License for the specific language governing permissions",
"as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config:",
"logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error classes; only one error",
"jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits =",
"| no exception) # logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits =",
"models.\"\"\" from typing import Any from flax import linen as nn import jax",
"either express or implied. # See the License for the specific language governing",
"config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder(",
"exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:,",
"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",
"= None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'],",
"raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple error classes; only one No-Error",
"the License. # You may obtain a copy of the License at #",
"config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask",
"config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact",
"num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer +",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"+ 1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) >",
"> 1: # Multiple No-Error classes; only one error class. if len(info.error_ids) >",
"No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e",
"encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings,",
"node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'],",
"else: docstring_embeddings = None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask,",
"# P(e | yes exception) # logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf)",
"= x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs",
"config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps self.node_span_encoder = spans.NodeSpanEncoder(",
"= x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens,",
"encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn =",
"docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask,",
"exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size #",
"info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size =",
"self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size =",
"= tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes,",
"# logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer +",
"Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size",
"self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps = config.max_steps",
"batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: #",
"with the License. # You may obtain a copy of the License at",
"self.config info = self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size,",
"self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config =",
"info = self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens",
"docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape:",
"raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig",
"if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0",
"self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn:",
"import linen as nn import jax import jax.numpy as jnp from core.data import",
"# no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings =",
"batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size # ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape:",
"no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape:",
"1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else:",
"batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size",
"info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer']",
"logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) #",
"self.docstring_token_encoder( docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32)",
"config.max_steps self.node_span_encoder = spans.NodeSpanEncoder( info=self.info, config=config, transformer_config=self.transformer_config, max_tokens=max_tokens, max_num_nodes=max_num_nodes, use_span_index_encoder=False, use_span_start_indicators=False, ) if",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"= info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception)",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask =",
"# raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) ==",
"== 1: # Multiple error classes; only one No-Error class. no_error_id = info.no_error_ids[0]",
"= ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config = self.config",
"= jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits",
"exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size",
"transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config = self.config vocab_size = self.info.vocab_size max_tokens =",
"logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: #",
"import jax import jax.numpy as jnp from core.data import error_kinds from core.modules.ipagnn import",
"docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) #",
"jnp from core.data import error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder",
"language governing permissions and # limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing",
"in compliance with the License. # You may obtain a copy of the",
"from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config:",
"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. #",
"exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size,",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"classes; only one error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes",
"transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self):",
"config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info,",
"See the License for the specific language governing permissions and # limitations under",
"raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using",
"= logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on data with no",
"num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer",
"import raise_contributions as raise_contributions_lib from third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info:",
"step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape: batch_size",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"nn import jax import jax.numpy as jnp from core.data import error_kinds from core.modules.ipagnn",
"encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder( docstring_tokens) docstring_mask",
"raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn import raise_contributions as raise_contributions_lib",
"self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'],",
"raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size",
"import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import",
"config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings'] # raise_node_embeddings.shape: batch_size, hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape:",
"0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings",
"dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings",
"No-Error classes; only one error class. if len(info.error_ids) > 1: raise NotImplementedError('Multiple error",
"# tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'],",
"# P(e | no exception) # logits.shape: batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf)",
"import Any from flax import linen as nn import jax import jax.numpy as",
"yes exception) # logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)(",
"= ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple error classes;",
"use_span_start_indicators=False, ) if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, )",
"# raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple error classes; only one",
"len(info.no_error_ids) > 1: # Multiple No-Error classes; only one error class. if len(info.error_ids)",
"one No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) #",
"from flax import linen as nn import jax import jax.numpy as jnp from",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"docstring_tokens) docstring_mask = docstring_tokens > 0 docstring_encoder_mask = nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) #",
"core.modules.ipagnn import ipagnn from core.modules.ipagnn import logit_math from core.modules.ipagnn import spans from core.modules.ipagnn",
"nn.make_attention_mask( docstring_mask, docstring_mask, dtype=jnp.float32) # docstring_token_embeddings.shape: batch_size, max_tokens, hidden_size docstring_embeddings = self.docstring_encoder( docstring_token_embeddings,",
"= ipagnn_output['exit_node_instruction_pointer'] # exit_node_instruction_pointer.shape: batch_size num_classes = info.num_classes if config.raise_in_ipagnn: raise_node_embeddings = ipagnn_output['raise_node_embeddings']",
"import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn from core.modules.ipagnn import",
"if len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and multiple no-error classes.') assert",
"limitations under the License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from flax import",
"error_id = info.error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # P(e | no",
"None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'],",
"# 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",
"docstring_tokens = x['docstring_tokens'] # tokens.shape: batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder(",
"jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits =",
"error_kinds from core.modules.ipagnn import compressive_ipagnn from core.modules.ipagnn import encoder from core.modules.ipagnn import ipagnn",
"= nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception) # logits.shape: batch_size,",
"docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'], true_indexes=x['true_branch_nodes'],",
"ipagnn.IPAGNNModule( info=self.info, config=config, max_steps=max_steps, ) @nn.compact def __call__(self, x): config = self.config info",
"batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception IPA-GNN on data",
"= self.info.vocab_size max_tokens = config.max_tokens max_num_nodes = config.max_num_nodes max_num_edges = config.max_num_edges max_steps =",
"License. \"\"\"IPA-GNN models.\"\"\" from typing import Any from flax import linen as nn",
"len(info.error_ids) > 1: raise NotImplementedError('Multiple error classes and multiple no-error classes.') assert len(info.error_ids)",
"None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'], edge_dests=x['edge_dests'], edge_types=x['edge_types'],",
"batch_size, num_classes logits = logits.at[:, error_id].set(-jnp.inf) error_logits = jax.vmap(logit_math.get_additional_logit)( raise_node_instruction_pointer + 1e-9, exit_node_instruction_pointer",
"docstring_embeddings = None docstring_mask = None ipagnn_output = self.ipagnn( node_embeddings=encoded_inputs, docstring_embeddings=docstring_embeddings, docstring_mask=docstring_mask, edge_sources=x['edge_sources'],",
"true_indexes=x['true_branch_nodes'], false_indexes=x['false_branch_nodes'], raise_indexes=x['raise_nodes'], start_node_indexes=x['start_index'], exit_node_indexes=x['exit_index'], post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size #",
"third_party.flax_examples import transformer_modules class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig",
"x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size if config.use_film or config.use_cross_attention: docstring_token_embeddings = self.docstring_token_encoder(",
"batch_size logits = logits.at[:, no_error_id].set(no_error_logits) elif len(info.no_error_ids) > 1: # Multiple No-Error classes;",
"docstring_embeddings = self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None ipagnn_output",
"batch_size if len(info.no_error_ids) == 1: # Multiple error classes; only one No-Error class.",
"+ 1e-9, raise_node_instruction_pointer + 1e-9, logits) # no_error_logits.shape: batch_size logits = logits.at[:, no_error_id].set(no_error_logits)",
"features=config.hidden_size, ) self.docstring_encoder = encoder.TransformerEncoder( config=self.docstring_transformer_config) if config.use_compressive_ipagnn: self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info,",
"as nn import jax import jax.numpy as jnp from core.data import error_kinds from",
"if config.use_film or config.use_cross_attention: self.docstring_token_encoder = encoder.TokenEncoder( transformer_config=self.docstring_transformer_config, num_embeddings=vocab_size, features=config.hidden_size, ) self.docstring_encoder =",
"= self.config info = self.info tokens = x['tokens'] docstring_tokens = x['docstring_tokens'] # tokens.shape:",
"hidden_size raise_node_instruction_pointer = ipagnn_output['raise_node_instruction_pointer'] # raise_node_instruction_pointer.shape: batch_size if len(info.no_error_ids) == 1: # Multiple",
"+ 1e-9, exit_node_instruction_pointer + 1e-9, logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits)",
"> 1: raise NotImplementedError('Multiple error classes and multiple no-error classes.') assert len(info.error_ids) ==",
"tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size",
"post_domination_matrix=x['post_domination_matrix'], step_limits=x['step_limit'], ) # ipagnn_output['exit_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['raise_node_embeddings'].shape: batch_size, hidden_size # ipagnn_output['exit_node_instruction_pointer'].shape:",
"only one No-Error class. no_error_id = info.no_error_ids[0] logits = nn.Dense( features=num_classes, name='output' )(raise_node_embeddings)",
"class IPAGNN(nn.Module): config: Any info: Any transformer_config: transformer_modules.TransformerConfig docstring_transformer_config: transformer_modules.TransformerConfig def setup(self): config",
"raise NotImplementedError('Multiple error classes and multiple no-error classes.') assert len(info.error_ids) == 1 error_id",
"# ipagnn_output['raise_node_instruction_pointer'].shape: batch_size exit_node_embeddings = ipagnn_output['exit_node_embeddings'] # exit_node_embeddings.shape: batch_size, hidden_size exit_node_instruction_pointer = ipagnn_output['exit_node_instruction_pointer']",
"logits) # error_logits.shape: batch_size logits = logits.at[:, error_id].set(error_logits) else: raise ValueError('Tried using Exception",
"name='output' )(exit_node_embeddings) # P(e | no exception) # logits.shape: batch_size, num_classes logits =",
"nn.Dense( features=num_classes, name='output' )(raise_node_embeddings) # P(e | yes exception) # logits.shape: batch_size, num_classes",
"\"\"\"IPA-GNN models.\"\"\" from typing import Any from flax import linen as nn import",
"logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer + 1e-9, raise_node_instruction_pointer + 1e-9, logits) #",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"self.docstring_encoder( docstring_token_embeddings, encoder_mask=docstring_encoder_mask) else: docstring_embeddings = None docstring_mask = None ipagnn_output = self.ipagnn(",
"@nn.compact def __call__(self, x): config = self.config info = self.info tokens = x['tokens']",
"batch_size, max_tokens batch_size = tokens.shape[0] encoded_inputs = self.node_span_encoder( tokens, x['node_token_span_starts'], x['node_token_span_ends'], x['num_nodes']) #",
"exception) # logits.shape: batch_size, num_classes logits = logits.at[:, no_error_id].set(-jnp.inf) no_error_logits = jax.vmap(logit_math.get_additional_logit)( exit_node_instruction_pointer",
"self.ipagnn = compressive_ipagnn.SkipIPAGNN( config=config, info=self.info, max_steps=max_steps, ) else: self.ipagnn = ipagnn.IPAGNNModule( info=self.info, config=config,",
"data with no errors.') else: logits = nn.Dense( features=num_classes, name='output' )(exit_node_embeddings) # logits.shape:"
] |
[
"runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\")",
"set runtime commands: build run build test run tests run run in environment",
"show script while running --dry-run show script without running --version show version project:",
"message --format set output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock",
"\"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help show",
"import unicode_literals def _(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV]",
"running --dry-run show script without running --version show version project: --env=ENV set env",
"run build test run tests run run in environment clean clean project files",
"commands: config show project configuration env show evaluable environment variables init generates project",
"project configuration env show evaluable environment variables init generates project skeleton runtime show",
"help message --format set output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage:",
"USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP =",
"set path --runtime=RUNTIME set runtime commands: build run build test run tests run",
"config show project configuration env show evaluable environment variables init generates project skeleton",
"version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime commands: build",
"show version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime commands:",
"--env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime commands: build run build",
"evaluable environment variables init generates project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE",
"_(\"\"\" --help show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\")",
"while running --dry-run show script without running --version show version project: --env=ENV set",
"clean project files other commands: config show project configuration env show evaluable environment",
"files other commands: config show project configuration env show evaluable environment variables init",
"run tests run run in environment clean clean project files other commands: config",
"project files other commands: config show project configuration env show evaluable environment variables",
"--runtime=RUNTIME set runtime commands: build run build test run tests run run in",
"unicode_literals def _(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH]",
"help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\"",
"command \"\"\") HELP = _(\"\"\" --help show help message --verbose show script while",
"return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\")",
"_(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\" --help show help message \"\"\")",
"_(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command",
"= _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help",
"[--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show help message --verbose",
"= _(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help show help message",
"from __future__ import unicode_literals def _(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock",
"project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config",
"_(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help",
"rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help message --format set",
"config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help message --format set output",
"show help message --verbose show script while running --dry-run show script without running",
"init generates project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage:",
"variables init generates project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\"",
"[--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show help message --verbose show",
"env --path=PATH set path --runtime=RUNTIME set runtime commands: build run build test run",
"\"\"\") CONFIG_HELP = _(\"\"\" --help show help message --format set output format (json,",
"script without running --version show version project: --env=ENV set env --path=PATH set path",
"env show evaluable environment variables init generates project skeleton runtime show installed runtimes",
"--version show version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime",
"HELP = _(\"\"\" --help show help message --verbose show script while running --dry-run",
"generates project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock",
"show script without running --version show version project: --env=ENV set env --path=PATH set",
"set env --path=PATH set path --runtime=RUNTIME set runtime commands: build run build test",
"commands: build run build test run tests run run in environment clean clean",
"env \"\"\") ENV_HELP = _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE = _(\"\"\"",
"run run in environment clean clean project files other commands: config show project",
"message --verbose show script while running --dry-run show script without running --version show",
"--path=PATH set path --runtime=RUNTIME set runtime commands: build run build test run tests",
"script while running --dry-run show script without running --version show version project: --env=ENV",
"environment clean clean project files other commands: config show project configuration env show",
"configuration env show evaluable environment variables init generates project skeleton runtime show installed",
"(json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\"",
"--help show help message --format set output format (json, yaml) \"\"\") ENV_USAGE =",
"tests run run in environment clean clean project files other commands: config show",
"test run tests run run in environment clean clean project files other commands:",
"show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP =",
"message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\" --help",
"help message --verbose show script while running --dry-run show script without running --version",
"yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help",
"set output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\")",
"RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\" --help show help",
"in environment clean clean project files other commands: config show project configuration env",
"ENV_HELP = _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock",
"= _(\"\"\" --help show help message --format set output format (json, yaml) \"\"\")",
"= _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\" --help show help message",
"show help message --format set output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\"",
"environment variables init generates project skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE =",
"skeleton runtime show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT]",
"project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set runtime commands: build run",
"output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP",
"\"\"\") ENV_HELP = _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage:",
"= _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime",
"run in environment clean clean project files other commands: config show project configuration",
"[--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show help message --verbose show script",
"Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE",
"path --runtime=RUNTIME set runtime commands: build run build test run tests run run",
"text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP",
"show evaluable environment variables init generates project skeleton runtime show installed runtimes \"\"\")",
"_(\"\"\" --help show help message --format set output format (json, yaml) \"\"\") ENV_USAGE",
"other commands: config show project configuration env show evaluable environment variables init generates",
"ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help show help",
"= _(\"\"\" --help show help message --verbose show script while running --dry-run show",
"CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show",
"show project configuration env show evaluable environment variables init generates project skeleton runtime",
"show installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP",
"_(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help message",
"runtime commands: build run build test run tests run run in environment clean",
"_(\"\"\" Usage: rock env \"\"\") ENV_HELP = _(\"\"\" --help show help message \"\"\")",
"rock env \"\"\") ENV_HELP = _(\"\"\" --help show help message \"\"\") RUNTIME_USAGE =",
"--format set output format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env",
"runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\"",
"def _(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME]",
"\"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help",
"= _(\"\"\" Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\"",
"rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show help",
"build run build test run tests run run in environment clean clean project",
"without running --version show version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME",
"[--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help message --format set output format",
"Usage: rock [--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show",
"\"\"\") HELP = _(\"\"\" --help show help message --verbose show script while running",
"Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP = _(\"\"\" --help show help message --format",
"installed runtimes \"\"\") CONFIG_USAGE = _(\"\"\" Usage: rock config [--format=FORMAT] \"\"\") CONFIG_HELP =",
"_(\"\"\" --help show help message --verbose show script while running --dry-run show script",
"clean clean project files other commands: config show project configuration env show evaluable",
"--verbose show script while running --dry-run show script without running --version show version",
"--help show help message \"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP",
"--dry-run show script without running --version show version project: --env=ENV set env --path=PATH",
"__future__ import unicode_literals def _(text): return text.strip('\\n') USAGE = _(\"\"\" Usage: rock [--help]",
"CONFIG_HELP = _(\"\"\" --help show help message --format set output format (json, yaml)",
"running --version show version project: --env=ENV set env --path=PATH set path --runtime=RUNTIME set",
"\"\"\") RUNTIME_USAGE = _(\"\"\" Usage: rock runtime \"\"\") RUNTIME_HELP = _(\"\"\" --help show",
"build test run tests run run in environment clean clean project files other",
"--help show help message --verbose show script while running --dry-run show script without",
"format (json, yaml) \"\"\") ENV_USAGE = _(\"\"\" Usage: rock env \"\"\") ENV_HELP =",
"[--help] [--env=ENV] [--path=PATH] [--runtime=RUNTIME] command \"\"\") HELP = _(\"\"\" --help show help message"
] |
[] |
[
"textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine",
"update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent) + \"%\")",
"class StatusBar: def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root = root",
"padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability:",
"label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self,",
"def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize() def",
"import Tkinter as tk class StatusBar: def __init__(self, root, label): self.label = tk.StringVar()",
"def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent) +",
"= tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN)",
"self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self): frame = tk.Frame(self.root,",
"pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability: \"",
"Tkinter as tk class StatusBar: def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label)",
"self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'),",
"= tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X)",
"label): percent = int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent) + \"%\") def",
"= tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label):",
"root, label): self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self): frame",
"tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label",
"relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def",
"label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability: \" +",
"root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12,",
"percent = int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent) + \"%\") def clear(self):",
"__init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self):",
"def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label,",
"12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100)",
"self.root = root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame,",
"as tk class StatusBar: def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root",
"frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent)",
"frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10)",
"label): self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize() def initialize(self): frame =",
"= root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial',",
"initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10,",
"tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent",
"tk class StatusBar: def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root =",
"self.label.set(label) self.root = root self.initialize() def initialize(self): frame = tk.Frame(self.root, relief=tk.SUNKEN) label =",
"font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent =",
"'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM) def update(self, label): percent = int(float(label)*100) self.label.set(\"No",
"= int(float(label)*100) self.label.set(\"No mine probability: \" + str(percent) + \"%\") def clear(self): self.label.set(\"\")",
"tk.Frame(self.root, relief=tk.SUNKEN) label = tk.Label(frame, font=('arial', 12, 'normal'), textvariable=self.label, padx=10, pady=10) label.pack(fill=tk.X) frame.pack(side=tk.BOTTOM)",
"StatusBar: def __init__(self, root, label): self.label = tk.StringVar() self.label.set(label) self.root = root self.initialize()"
] |
[
"parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing",
"\"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import",
"configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of",
"args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if",
"of Haplotype Caller threads (per region cluster).\" \" Values>1 reported to make Haplotype",
"level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG #",
"logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\"",
"raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject",
"aux_logger from pipelines import get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__ =",
"if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples for joint calling\") sys.exit(1)",
"logger.fatal(\"Analysis of exome and targeted sequence runs requires a bed file\") sys.exit(1) else:",
"pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\"",
"get_readunits_from_args from pipelines import get_pipeline_version from pipelines import PipelineHandler from pipelines import logger",
"needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM",
"target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"):",
"\"\"\"{PIPELINE_NAME} pipeline (version: {PIPELINE_VERSION}): creates pipeline-specific config files to given output directory and",
"the pipeline (unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced",
"from pipelines import logger as aux_logger from pipelines import get_cluster_cfgfile from pipelines import",
"only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\")",
"joint calling\") sys.exit(1) # turn arguments into cfg_dict (gets merged with other configs",
"filename has to match definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\",",
"(per region cluster).\" \" Values>1 reported to make Haplotype Caller unstable (default={})\".format(default)) default",
"if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls:",
"WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct']",
"# script -vv -> DEBUG # script -v -> INFO # script ->",
"list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files as argument if not using",
"not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR",
"exome and targeted sequence runs requires a bed file\") sys.exit(1) else: if not",
"target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif",
"config, so input is either fastq or existing bam samples = dict() if",
"least two samples for joint calling\") sys.exit(1) # turn arguments into cfg_dict (gets",
"%s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least",
"pipelines import get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__ = \"<NAME>\" __email__",
"handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser",
"readunit keys as value. readunits is a dict with # readunits (think: fastq",
"import PipelineHandler from pipelines import logger as aux_logger from pipelines import get_cluster_cfgfile from",
"args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam,",
"'[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser =",
"Required for WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int,",
"True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name.",
"if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target",
"\".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) +",
"of interest.\" \" Required for WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\",",
"make Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding",
"action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR",
"WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR",
"10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) #",
"args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target +=",
"threads (per region cluster).\" \" Values>1 reported to make Haplotype Caller unstable (default={})\".format(default))",
"from pipelines import get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__ = \"<NAME>\"",
"region cluster).\" \" Values>1 reported to make Haplotype Caller unstable (default={})\".format(default)) default =",
"parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES',",
"one sample specified on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least",
"\"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\")",
"turn arguments into cfg_dict (gets merged with other configs late) # cfg_dict =",
"and pre-processing need to match pipeline requirements\") # FIXME can be achieved with",
"to given output directory and runs the pipeline (unless otherwise requested). \"\"\" #",
"replaced while # printing usage #--- standard library imports # import sys import",
"job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global logger logger =",
"\" WARNING: reference and pre-processing need to match pipeline requirements\") # FIXME can",
"for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only",
"sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1)",
"cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict,",
"cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler",
"parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args",
"up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\") args",
"args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam)",
"import default_argparser import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016",
"# turn arguments into cfg_dict (gets merged with other configs late) # cfg_dict",
"\" Required for WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default,",
"CRITICAL # script -qqq -> no logging at all logger.setLevel(logging.WARN + 10*args.quiet -",
"import logger as aux_logger from pipelines import get_cluster_cfgfile from pipelines import default_argparser import",
"generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage #--- standard library",
"\"cfg\") # same as folder name. also used for cluster job names PIPELINE_NAME",
"at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if",
"os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target =",
"argument if not using config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if",
"if args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and targeted",
"args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env()",
"up until GVCF file\") args = parser.parse_args() # Repeateable -v and -q for",
"directory and runs the pipeline (unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME}",
"assert not args.proc_bam, (\"Cannot inject raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam)",
"fastq or existing bam samples = dict() if not args.sample: logger.fatal(\"Need sample name",
"'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\" \"",
"= os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH)",
"does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two",
"command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files as argument",
"script -v -> INFO # script -> WARNING # script -q -> ERROR",
"from pipelines import default_argparser import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__",
"= lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same",
"style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser =",
"name if not using config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not",
"# same as folder name. also used for cluster job names PIPELINE_NAME =",
"exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input",
"# generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage #--- standard",
"LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import",
"{PIPELINE_VERSION}): creates pipeline-specific config files to given output directory and runs the pipeline",
"aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir)",
"help=\"Only process up until GVCF file\") args = parser.parse_args() # Repeateable -v and",
"--until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only',",
"achieved with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM",
"requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage",
"os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and processed BAM\") if args.proc_bam: assert",
"= dict() if not args.sample: logger.fatal(\"Need sample name if not using config file\")",
"do not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0])",
"+= \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target",
"imports # import yaml #--- project specific imports # # add lib dir",
"process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\")",
"not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if",
"\"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\" __license__ = \"The MIT License",
"None# always safe, might be used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS",
"sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines",
"https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script -v -> INFO # script",
"is a dict with # readunits (think: fastq pairs with attributes) as value",
"sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is either",
"logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main():",
"usage #--- standard library imports # import sys import os import logging #---",
"os import logging #--- third-party imports # import yaml #--- project specific imports",
"add lib dir for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)),",
"in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs",
"runs the pipeline (unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION}",
"import os import logging #--- third-party imports # import yaml #--- project specific",
"files as argument if not using config file\") sys.exit(1) if args.seqtype in ['WES',",
"existing BAM by symlinking (everything upstream is temporary anyway) # WARNING: filename has",
"default_argparser import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome",
"Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS",
"specified on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one fastq",
"into this one sample specified on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need",
"either fastq or existing bam samples = dict() if not args.sample: logger.fatal(\"Need sample",
"BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and processed",
"same as folder name. also used for cluster job names PIPELINE_NAME = \"gatk\"",
"= parser.parse_args() # Repeateable -v and -q for setting logging level. # See",
"yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") #",
"fastq pairs with attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam,",
"help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.)",
"assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits =",
"not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits =",
"(overwrites fq options).\" \" WARNING: reference and pre-processing need to match pipeline requirements\")",
"all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir):",
"(mostly just # one) and readunit keys as value. readunits is a dict",
"= os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] !=",
"specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed",
"assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and processed BAM\") if args.proc_bam:",
"(\"Cannot inject raw and processed BAM\") readunits = dict() samples[args.sample] = [] elif",
"logger.fatal(\"Need at least one fastq files as argument if not using config file\")",
"args.bed else None# always safe, might be used for WGS as well cfg_dict['mark_dups']",
"\"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target",
"padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling",
"samples = dict() if not args.sample: logger.fatal(\"Need sample name if not using config",
"import get_pipeline_version from pipelines import PipelineHandler from pipelines import logger as aux_logger from",
"args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\" \"",
"(post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference and pre-processing need",
"using config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection",
"= logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def",
"not args.proc_bam, (\"Cannot inject raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert",
"= os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target",
"in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target)",
"pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\",",
"can be achieved with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up",
"get_pipeline_version from pipelines import PipelineHandler from pipelines import logger as aux_logger from pipelines",
"dict() if not args.sample: logger.fatal(\"Need sample name if not using config file\") sys.exit(1)",
"etc.) BAM (overwrites fq options).\" \" WARNING: reference and pre-processing need to match",
"processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and",
"-qq -> CRITICAL # script -qqq -> no logging at all logger.setLevel(logging.WARN +",
"for WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number",
"not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so",
"processed BAM\") readunits = dict() samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1,",
"file %s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at",
"{PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage #--- standard library imports #",
"= os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also used for cluster job",
"the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files as",
"on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files",
"if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai =",
"dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed)",
"if not args.sample: logger.fatal(\"Need sample name if not using config file\") sys.exit(1) if",
"*args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder",
"\"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title =",
"imports # # add lib dir for this pipeline installation to PYTHONPATH LIB_PATH",
"if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample,",
"logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:#",
"INFO # script -> WARNING # script -q -> ERROR # script -qq",
"os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2:",
"calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites",
"if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits",
"from pipelines import PipelineHandler from pipelines import logger as aux_logger from pipelines import",
"-> DEBUG # script -v -> INFO # script -> WARNING # script",
"cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if",
"cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything upstream is temporary",
"readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import get_pipeline_version from pipelines",
"args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits",
"not args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not",
"names as key (mostly just # one) and readunit keys as value. readunits",
"# # add lib dir for this pipeline installation to PYTHONPATH LIB_PATH =",
"at least one fastq files as argument if not using config file\") sys.exit(1)",
"two samples for joint calling\") sys.exit(1) # turn arguments into cfg_dict (gets merged",
"pipeline-specific config files to given output directory and runs the pipeline (unless otherwise",
"#--- third-party imports # import yaml #--- project specific imports # # add",
"targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller",
"__author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\"",
"injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject",
"BAM by symlinking (everything upstream is temporary anyway) # WARNING: filename has to",
"symlinking (everything upstream is temporary anyway) # WARNING: filename has to match definition",
"os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg)",
"= get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this one sample specified on",
"file overrides fastq, sample and BAM arguments.\" \" Use one or the other\")",
"logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)",
"fastq files as argument if not using config file\") sys.exit(1) if args.seqtype in",
"args = parser.parse_args() # Repeateable -v and -q for setting logging level. #",
"file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg)",
"script -qqq -> no logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN",
"be achieved with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until",
"for joint calling\") sys.exit(1) # turn arguments into cfg_dict (gets merged with other",
"-> INFO # script -> WARNING # script -q -> ERROR # script",
"\"2016 Genome Institute of Singapore\" __license__ = \"The MIT License (MIT)\" # only",
"= args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler =",
"standard library imports # import sys import os import logging #--- third-party imports",
"FIXME can be achieved with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process",
"# printing usage #--- standard library imports # import sys import os import",
"# script -qqq -> no logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)",
"not args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs requires a bed file\")",
"readunits go into this one sample specified on the command-line samples[args.sample] = list(readunits.keys())",
"yaml #--- project specific imports # # add lib dir for this pipeline",
"one fastq files as argument if not using config file\") sys.exit(1) if args.seqtype",
"default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\"",
"PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True,",
"is either fastq or existing bam samples = dict() if not args.sample: logger.fatal(\"Need",
"cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls']",
"requirements\") # FIXME can be achieved with --until rule as well parser.add_argument('--bam-only', action='store_true',",
"sample name if not using config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert",
"args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this one sample",
"= \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\" __license__",
"target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype']",
"library imports # import sys import os import logging #--- third-party imports #",
"args.outdir) sys.exit(1) # samples is a dictionary with sample names as key (mostly",
"script -qq -> CRITICAL # script -qqq -> no logging at all logger.setLevel(logging.WARN",
"upstream is temporary anyway) # WARNING: filename has to match definition in Snakefile!",
"-q -> ERROR # script -qq -> CRITICAL # script -qqq -> no",
"+ \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target",
"file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\") args = parser.parse_args() #",
"output directory and runs the pipeline (unless otherwise requested). \"\"\" # generic usage",
"import logging #--- third-party imports # import yaml #--- project specific imports #",
"\"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from",
"len(samples)<2: logger.fatal(\"Need at least two samples for joint calling\") sys.exit(1) # turn arguments",
"not using config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM",
"as argument if not using config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']:",
"parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\") args = parser.parse_args() # Repeateable",
"https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script -v ->",
"= dict() samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all",
"args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and",
"\" Values>1 reported to make Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i',",
"from readunits import get_readunits_from_args from pipelines import get_pipeline_version from pipelines import PipelineHandler from",
"help=\"Bed file listing regions of interest.\" \" Required for WES and targeted sequencing.\")",
"the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg)",
"# cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype",
"import sys import os import logging #--- third-party imports # import yaml #---",
"and -q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 #",
"logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{'))",
"= 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads (per region",
"logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) # samples is a dictionary with",
"or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert",
"if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run) if __name__",
"joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM",
"interest.\" \" Required for WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\",",
"using config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis",
"parser.parse_args() # Repeateable -v and -q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/",
"logger as aux_logger from pipelines import get_cluster_cfgfile from pipelines import default_argparser import configargparse",
"os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample))",
"4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads (per region cluster).\"",
"= \"The MIT License (MIT)\" # only dump() and following do not automatically",
"setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv ->",
"specific imports # # add lib dir for this pipeline installation to PYTHONPATH",
"args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing",
"at least two samples for joint calling\") sys.exit(1) # turn arguments into cfg_dict",
"(requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq",
"cluster).\" \" Values>1 reported to make Haplotype Caller unstable (default={})\".format(default)) default = 100",
"arguments into cfg_dict (gets merged with other configs late) # cfg_dict = dict()",
"create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR,",
"BAM arguments.\" \" Use one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config",
"late) # cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] =",
"else None# always safe, might be used for WGS as well cfg_dict['mark_dups'] =",
"match definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target))",
"exists\", args.outdir) sys.exit(1) # samples is a dictionary with sample names as key",
"elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this one",
"#!/usr/bin/env python3 \"\"\"{PIPELINE_NAME} pipeline (version: {PIPELINE_VERSION}): creates pipeline-specific config files to given output",
"__email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\" __license__ = \"The",
"= \"gatk\" MARK_DUPS = True # global logger logger = logging.getLogger(__name__) handler =",
"See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script -v",
"PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also",
"BAM\") readunits = dict() samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2)",
"reference and pre-processing need to match pipeline requirements\") # FIXME can be achieved",
"= [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go into",
"a bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not",
"cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals']",
"get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is either fastq or existing bam",
"PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global logger logger = logging.getLogger(__name__) handler",
"cfg_dict (gets merged with other configs late) # cfg_dict = dict() cfg_dict['readunits'] =",
"args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always safe, might be used",
"(MIT)\" # only dump() and following do not automatically create aliases yaml.Dumper.ignore_aliases =",
"pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything upstream is temporary anyway) #",
"= os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also used",
"with attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config",
"os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run) if __name__ ==",
"{PIPELINE_VERSION} replaced while # printing usage #--- standard library imports # import sys",
"Genome Institute of Singapore\" __license__ = \"The MIT License (MIT)\" # only dump()",
"parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\",",
"exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples for",
"so input is either fastq or existing bam samples = dict() if not",
"args.fq2) # all readunits go into this one sample specified on the command-line",
"WARNING: filename has to match definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir,",
"pipelines import PipelineHandler from pipelines import logger as aux_logger from pipelines import get_cluster_cfgfile",
"logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need",
"PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything",
"pipeline (version: {PIPELINE_VERSION}): creates pipeline-specific config files to given output directory and runs",
"dict() samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits",
"default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default =",
"sys.exit(1) # samples is a dictionary with sample names as key (mostly just",
"with other configs late) # cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] =",
"existing bam samples = dict() if not args.sample: logger.fatal(\"Need sample name if not",
"pipeline requirements\") # FIXME can be achieved with --until rule as well parser.add_argument('--bam-only',",
"else:# no sample config, so input is either fastq or existing bam samples",
"default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam',",
"of exome and targeted sequence runs requires a bed file\") sys.exit(1) else: if",
"dir for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\",",
"help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF",
"Haplotype Caller threads (per region cluster).\" \" Values>1 reported to make Haplotype Caller",
"(gets merged with other configs late) # cfg_dict = dict() cfg_dict['readunits'] = readunits",
"'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\" \" Required",
"config files to given output directory and runs the pipeline (unless otherwise requested).",
"inject raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot",
"automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR =",
"if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq arguments\") if",
"os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\")",
"= 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default = {})\".format(default))",
"(overwrites fq options).\" \" WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced:",
"args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and processed BAM\") if",
"not args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits = dict() samples[args.sample] =",
"cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() #",
"args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything upstream is",
"# samples is a dictionary with sample names as key (mostly just #",
"ERROR # script -qq -> CRITICAL # script -qqq -> no logging at",
"if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM",
"{})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects",
"as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only",
"target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target += \".bam\"",
"samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files as argument if",
"= args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always safe, might be",
"already exists\", args.outdir) sys.exit(1) # samples is a dictionary with sample names as",
"a dictionary with sample names as key (mostly just # one) and readunit",
"does not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config,",
"global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}',",
"'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) +",
"pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference needs to match pipeline",
"also used for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True #",
"args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is",
"default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads (per",
"cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything upstream is temporary anyway)",
"used for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global",
"file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq",
"sample config, so input is either fastq or existing bam samples = dict()",
"# script -qq -> CRITICAL # script -qqq -> no logging at all",
"if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and processed BAM\")",
"# add lib dir for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath(",
"# script -> WARNING # script -q -> ERROR # script -qq ->",
"this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if",
"script -q -> ERROR # script -qq -> CRITICAL # script -qqq ->",
"readunits (think: fastq pairs with attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2,",
"input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \"",
"overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw",
"to match definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample))",
"sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1) samples,",
"(version: {PIPELINE_VERSION}): creates pipeline-specific config files to given output directory and runs the",
"help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference",
"# and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script -v -> INFO",
"else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\", args.sample_cfg) sys.exit(1) if",
"samples for joint calling\") sys.exit(1) # turn arguments into cfg_dict (gets merged with",
"sys import os import logging #--- third-party imports # import yaml #--- project",
"= args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject",
"temporary anyway) # WARNING: filename has to match definition in Snakefile! if args.raw_bam:",
"Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai",
"target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) +",
"PipelineHandler from pipelines import logger as aux_logger from pipelines import get_cluster_cfgfile from pipelines",
"Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference and",
"is temporary anyway) # WARNING: filename has to match definition in Snakefile! if",
"samples is a dictionary with sample names as key (mostly just # one)",
"(for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires",
"regions of interest.\" \" Required for WES and targeted sequencing.\") default = 4",
"file %s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no",
"pipelines import default_argparser import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ =",
"in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from",
"License (MIT)\" # only dump() and following do not automatically create aliases yaml.Dumper.ignore_aliases",
"os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted':",
"\"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target",
"function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title",
"cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None#",
"following do not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR =",
"of Singapore\" __license__ = \"The MIT License (MIT)\" # only dump() and following",
"need to match pipeline requirements\") # FIXME can be achieved with --until rule",
"options).\" \" WARNING: reference and pre-processing need to match pipeline requirements\") # FIXME",
"- 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already",
"default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline",
"target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']:",
"not exist\", args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples",
"name. also used for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True",
"sample and BAM arguments.\" \" Use one or the other\") sys.exit(1) if not",
"might be used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only",
"inject raw and processed BAM\") readunits = dict() samples[args.sample] = [] elif args.fq1:",
"\".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target +",
"script -vv -> DEBUG # script -v -> INFO # script -> WARNING",
"# WARNING: filename has to match definition in Snakefile! if args.raw_bam: target =",
"\"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage #---",
"options).\" \" WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed",
"10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\",",
"and readunit keys as value. readunits is a dict with # readunits (think:",
"os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\")",
"has to match definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample,",
"import get_readunits_from_args from pipelines import get_pipeline_version from pipelines import PipelineHandler from pipelines import",
"BAM (overwrites fq options).\" \" WARNING: reference and pre-processing need to match pipeline",
"# script -v -> INFO # script -> WARNING # script -q ->",
"fq options).\" \" WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects",
"\"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser])",
"given output directory and runs the pipeline (unless otherwise requested). \"\"\" # generic",
"get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this one sample specified on the",
"pipelines import logger as aux_logger from pipelines import get_cluster_cfgfile from pipelines import default_argparser",
"= args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR,",
"any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\"",
"{filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True)",
"args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\" \" Use one or",
"multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\"",
"cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME,",
"(\"Cannot inject raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam,",
"cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if",
"parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING:",
"and processed BAM\") readunits = dict() samples[args.sample] = [] elif args.fq1: readunits =",
"action='store_true', help=\"Only process up until GVCF file\") args = parser.parse_args() # Repeateable -v",
"%s already exists\", args.outdir) sys.exit(1) # samples is a dictionary with sample names",
"to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites",
"logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output",
"dict with # readunits (think: fastq pairs with attributes) as value if args.sample_cfg:",
"args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits = dict() samples[args.sample] = []",
"to match pipeline requirements\") # FIXME can be achieved with --until rule as",
"else: logger.fatal(\"Need at least one fastq files as argument if not using config",
"if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits",
"required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of",
"= \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing",
"# pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l',",
"-q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script",
"import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import get_pipeline_version from pipelines import",
"# Inject existing BAM by symlinking (everything upstream is temporary anyway) # WARNING:",
"args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai,",
"os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target +",
"assert not args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits = dict() samples[args.sample]",
"logger.fatal(\"Need at least two samples for joint calling\") sys.exit(1) # turn arguments into",
"third-party imports # import yaml #--- project specific imports # # add lib",
"PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS',",
"for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global logger",
"installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not",
"sample specified on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at least one",
"post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference and pre-processing need to",
"100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j',",
"handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main",
"fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and",
"value. readunits is a dict with # readunits (think: fastq pairs with attributes)",
"Inject existing BAM by symlinking (everything upstream is temporary anyway) # WARNING: filename",
"(default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default",
"least one fastq files as argument if not using config file\") sys.exit(1) if",
"file\") args = parser.parse_args() # Repeateable -v and -q for setting logging level.",
"%s does not exist\", args.sample_cfg) sys.exit(1) samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample",
"= {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced:",
"until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\") args =",
"files to given output directory and runs the pipeline (unless otherwise requested). \"\"\"",
"raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference needs to",
"args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam:",
"PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking",
"= PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by",
"folder name. also used for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS =",
"WARNING: reference and pre-processing need to match pipeline requirements\") # FIXME can be",
"\"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile",
"project specific imports # # add lib dir for this pipeline installation to",
"requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \"",
"all readunits go into this one sample specified on the command-line samples[args.sample] =",
"usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing usage #--- standard library imports",
"\".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target +=",
"os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from",
"choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\"",
"for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\"))",
"{levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR,",
"logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler)",
"match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq",
"this one sample specified on the command-line samples[args.sample] = list(readunits.keys()) else: logger.fatal(\"Need at",
"Values>1 reported to make Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\",",
"pairs with attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]):",
"Institute of Singapore\" __license__ = \"The MIT License (MIT)\" # only dump() and",
"WARNING # script -q -> ERROR # script -qq -> CRITICAL # script",
"elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\"",
"logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG",
"-vv -> DEBUG # script -v -> INFO # script -> WARNING #",
"\"The MIT License (MIT)\" # only dump() and following do not automatically create",
"if not args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs requires a bed",
"(unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while #",
"-v -> INFO # script -> WARNING # script -q -> ERROR #",
"= get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is either fastq or existing",
"args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args,",
"one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not",
"import get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__ = \"<NAME>\" __email__ =",
"\"{}.bwamem\".format(args.sample)) if cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\"",
"DEBUG # script -v -> INFO # script -> WARNING # script -q",
"as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides",
"= default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" #",
"readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is either fastq or",
"def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME,",
"from pipelines import get_pipeline_version from pipelines import PipelineHandler from pipelines import logger as",
"requires a bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does",
"10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s",
"LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0,",
"target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\",",
"sys.exit(1) # turn arguments into cfg_dict (gets merged with other configs late) #",
"# only dump() and following do not automatically create aliases yaml.Dumper.ignore_aliases = lambda",
"with # readunits (think: fastq pairs with attributes) as value if args.sample_cfg: if",
"get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import get_pipeline_version from pipelines import PipelineHandler",
"src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam:",
"and following do not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR",
"for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv",
"parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'],",
"raw and processed BAM\") readunits = dict() samples[args.sample] = [] elif args.fq1: readunits",
"targeted sequence runs requires a bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed",
"= True # global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}]",
"sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples for joint calling\")",
"readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this one sample specified",
"process up until GVCF file\") args = parser.parse_args() # Repeateable -v and -q",
"with sample names as key (mostly just # one) and readunit keys as",
"lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as",
"listing regions of interest.\" \" Required for WES and targeted sequencing.\") default =",
"os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) # samples is a dictionary",
"and targeted sequence runs requires a bed file\") sys.exit(1) else: if not os.path.exists(args.bed):",
"Singapore\" __license__ = \"The MIT License (MIT)\" # only dump() and following do",
"\".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\",",
"help=\"Interval padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort",
"parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\" \" Required for WES and",
"__copyright__ = \"2016 Genome Institute of Singapore\" __license__ = \"The MIT License (MIT)\"",
"# script -q -> ERROR # script -qq -> CRITICAL # script -qqq",
"and runs the pipeline (unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and",
"assert not args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert",
"os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also used for cluster job names",
"as key (mostly just # one) and readunit keys as value. readunits is",
"default=default, type=int, help=\"Number of Haplotype Caller threads (per region cluster).\" \" Values>1 reported",
"['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs requires",
"with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific",
"\".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run) if __name__ == \"__main__\": main()",
"not args.sample: logger.fatal(\"Need sample name if not using config file\") sys.exit(1) if args.raw_bam",
"script -> WARNING # script -q -> ERROR # script -qq -> CRITICAL",
"default=default, help=\"Interval padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform",
"readunits is a dict with # readunits (think: fastq pairs with attributes) as",
"+ 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1)",
"action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until",
"attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file",
"bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s does not exist\",",
"\".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam),",
"os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem\".format(args.sample)) if",
"one) and readunit keys as value. readunits is a dict with # readunits",
"os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw and processed BAM\") readunits = dict()",
"not using config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not args.bed:",
"pre-processing need to match pipeline requirements\") # FIXME can be achieved with --until",
"args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler(",
"readunits = dict() samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) #",
"reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.)",
"+ \".bai\" if os.path.exists(src_bai): os.symlink(src_bai, target + \".bai\") elif args.proc_bam: target = os.path.join(args.outdir,",
"10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) # samples is",
"\"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw (pre-dedup,",
"BAM (overwrites fq options).\" \" WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam',",
"\"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads (per region cluster).\" \" Values>1",
"= list(readunits.keys()) else: logger.fatal(\"Need at least one fastq files as argument if not",
"'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs requires a",
"\"--bed\", help=\"Bed file listing regions of interest.\" \" Required for WES and targeted",
"as aux_logger from pipelines import get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__",
"python3 \"\"\"{PIPELINE_NAME} pipeline (version: {PIPELINE_VERSION}): creates pipeline-specific config files to given output directory",
"MIT License (MIT)\" # only dump() and following do not automatically create aliases",
"bam samples = dict() if not args.sample: logger.fatal(\"Need sample name if not using",
"samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always safe,",
"not in sys.path: sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args",
"from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import get_pipeline_version from",
"and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not args.raw_bam, (\"Cannot inject raw",
"args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\" \" Use one",
"Repeateable -v and -q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and",
"= \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\" __license__ = \"The MIT",
"logging #--- third-party imports # import yaml #--- project specific imports # #",
"(think: fastq pairs with attributes) as value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample,",
"args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples for joint calling\") sys.exit(1) #",
"= args.joint_calls cfg_dict['interval_padding'] = args.interval_padding pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR))",
"dump() and following do not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args: True",
"Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference needs",
"used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] =",
"# import sys import os import logging #--- third-party imports # import yaml",
"target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run) if",
"is a dictionary with sample names as key (mostly just # one) and",
"args.proc_bam, (\"Cannot inject raw and processed BAM\") if args.proc_bam: assert os.path.exists(args.proc_bam) assert not",
"cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always safe, might be used for",
"and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script -v -> INFO #",
"type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\" \" Required for WES",
"match pipeline requirements\") # FIXME can be achieved with --until rule as well",
"parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample input)\") parser.add_argument('--raw-bam', help=\"Advanced: Injects raw",
"until GVCF file\") args = parser.parse_args() # Repeateable -v and -q for setting",
"etc.) BAM (overwrites fq options).\" \" WARNING: reference needs to match pipeline requirements\")",
"as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] =",
"= \"2016 Genome Institute of Singapore\" __license__ = \"The MIT License (MIT)\" #",
"\" Use one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s",
"sample names as key (mostly just # one) and readunit keys as value.",
"os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also used for",
"directory %s already exists\", args.outdir) sys.exit(1) # samples is a dictionary with sample",
"-> CRITICAL # script -qqq -> no logging at all logger.setLevel(logging.WARN + 10*args.quiet",
"-> no logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet",
"overrides fastq, sample and BAM arguments.\" \" Use one or the other\") sys.exit(1)",
"\" WARNING: reference needs to match pipeline requirements\") parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup,",
"-qqq -> no logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN +",
"help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions of interest.\" \" Required for",
"processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference and pre-processing",
"merged with other configs late) # cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples']",
"readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else",
"+ 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory",
"sys.path.insert(0, LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import",
"= logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename} {message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function",
"parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads (per region cluster).\" \"",
"os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if",
"samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg) else:# no sample config, so input is either fastq",
"if not using config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not",
"\"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute of Singapore\" __license__ =",
"other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\", args.sample_cfg) sys.exit(1)",
"fq options).\" \" WARNING: reference and pre-processing need to match pipeline requirements\") #",
"no sample config, so input is either fastq or existing bam samples =",
"(everything upstream is temporary anyway) # WARNING: filename has to match definition in",
"Use one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does",
"__license__ = \"The MIT License (MIT)\" # only dump() and following do not",
"if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample",
"\"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file listing regions",
"PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path:",
"input is either fastq or existing bam samples = dict() if not args.sample:",
"pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH",
"with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\")",
"args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] = args.interval_padding",
"sequence runs requires a bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file",
"# FIXME can be achieved with --until rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only",
"= configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t',",
"reported to make Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default,",
"args.bed: logger.fatal(\"Analysis of exome and targeted sequence runs requires a bed file\") sys.exit(1)",
"non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true', help=\"Perform joint/cohort calling (requires multisample",
"file listing regions of interest.\" \" Required for WES and targeted sequencing.\") default",
"# one) and readunit keys as value. readunits is a dict with #",
"file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome",
"configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()), parents=[default_parser]) parser._optionals.title = \"Arguments\" # pipeline specific args parser.add_argument('-t', \"--seqtype\",",
"sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq arguments\")",
"into cfg_dict (gets merged with other configs late) # cfg_dict = dict() cfg_dict['readunits']",
"args parser.add_argument('-t', \"--seqtype\", required=True, choices=['WGS', 'WES', 'targeted'], help=\"Sequencing type\") parser.add_argument('-l', \"--bed\", help=\"Bed file",
"type=int, help=\"Number of Haplotype Caller threads (per region cluster).\" \" Values>1 reported to",
"# readunits (think: fastq pairs with attributes) as value if args.sample_cfg: if any([args.fq1,",
"configs late) # cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype']",
"sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and",
"!= 'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam)",
"and BAM arguments.\" \" Use one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg):",
"# all readunits go into this one sample specified on the command-line samples[args.sample]",
"+= \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam)",
"just # one) and readunit keys as value. readunits is a dict with",
"[] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go into this",
"be used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only']",
"= os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\"",
"os.symlink(os.path.abspath(args.proc_bam), target) if os.path.exists(os.path.abspath(args.proc_bam) + \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run)",
"+ \".bai\"): os.symlink(os.path.abspath(args.proc_bam) + \".bai\", target + \".bai\") pipeline_handler.submit(args.no_run) if __name__ == \"__main__\":",
"go into this one sample specified on the command-line samples[args.sample] = list(readunits.keys()) else:",
"#--- standard library imports # import sys import os import logging #--- third-party",
"fastq, sample and BAM arguments.\" \" Use one or the other\") sys.exit(1) if",
"no logging at all logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose) aux_logger.setLevel(logging.WARN + 10*args.quiet -",
"cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global logger logger",
"Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for",
"+= \".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target))",
"Caller threads (per region cluster).\" \" Values>1 reported to make Haplotype Caller unstable",
"other configs late) # cfg_dict = dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples",
"well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct",
"= samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always",
"while # printing usage #--- standard library imports # import sys import os",
"samples[args.sample] = [] elif args.fq1: readunits = get_readunits_from_args(args.fq1, args.fq2) # all readunits go",
"# import yaml #--- project specific imports # # add lib dir for",
"printing usage #--- standard library imports # import sys import os import logging",
"main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format( PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()),",
"definition in Snakefile! if args.raw_bam: target = os.path.join(args.outdir, \"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam),",
"\"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only; default = {})\".format(default)) parser.add_argument('-j', \"--joint-calls\", action='store_true',",
"keys as value. readunits is a dict with # readunits (think: fastq pairs",
"= MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] =",
"always safe, might be used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only']",
"args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of exome and targeted sequence",
"otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while # printing",
"WES and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of",
"or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file %s does not exist\",",
"os.path.abspath(args.bed) if args.bed else None# always safe, might be used for WGS as",
"CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\") # same as folder name. also used for cluster",
"by symlinking (everything upstream is temporary anyway) # WARNING: filename has to match",
"-> ERROR # script -qq -> CRITICAL # script -qqq -> no logging",
"if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and processed BAM\")",
"(pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference needs to match",
"help=\"Advanced: Injects raw (pre-dedup, pre-BQSR etc.) BAM (overwrites fq options).\" \" WARNING: reference",
"arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot inject raw and processed",
"to make Haplotype Caller unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval",
"a dict with # readunits (think: fastq pairs with attributes) as value if",
"args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\" \" Use",
"or existing bam samples = dict() if not args.sample: logger.fatal(\"Need sample name if",
"anyway) # WARNING: filename has to match definition in Snakefile! if args.raw_bam: target",
"cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding']",
"config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1, (\"BAM injection overwrites",
"os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in sys.path: sys.path.insert(0, LIB_PATH) from readunits",
"unstable (default={})\".format(default)) default = 100 parser.add_argument('-i', \"--interval-padding\", default=default, help=\"Interval padding (for non-WGS only;",
"key (mostly just # one) and readunit keys as value. readunits is a",
"if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target += \".bam\" os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.proc_bam), target)",
"args.proc_bam: assert not args.fq1, (\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam)",
"= dict() cfg_dict['readunits'] = readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] =",
"cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed else None# always safe, might",
"= os.path.abspath(args.bed) if args.bed else None# always safe, might be used for WGS",
"to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"lib\")) if LIB_PATH not in",
"\"gatk\" MARK_DUPS = True # global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler()",
"sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype Caller threads",
"rule as well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true',",
"names PIPELINE_NAME = \"gatk\" MARK_DUPS = True # global logger logger = logging.getLogger(__name__)",
"safe, might be used for WGS as well cfg_dict['mark_dups'] = MARK_DUPS cfg_dict['bam_only'] =",
"if args.bed else None# always safe, might be used for WGS as well",
"pipeline_handler = PipelineHandler( PIPELINE_NAME, PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM",
"- 10*args.verbose) if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) # samples",
"help=\"Number of Haplotype Caller threads (per region cluster).\" \" Values>1 reported to make",
"PIPELINE_BASEDIR, args, cfg_dict, cluster_cfgfile=get_cluster_cfgfile(CFG_DIR)) pipeline_handler.setup_env() # Inject existing BAM by symlinking (everything upstream",
"MARK_DUPS cfg_dict['bam_only'] = args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls",
"MARK_DUPS = True # global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(",
"aliases yaml.Dumper.ignore_aliases = lambda *args: True PIPELINE_BASEDIR = os.path.dirname(sys.argv[0]) CFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\")",
"parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up",
"# See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4 # script -vv -> DEBUG # script",
"value if args.sample_cfg: if any([args.fq1, args.fq2, args.sample, args.raw_bam, args.proc_bam]): logger.fatal(\"Config file overrides fastq,",
"args.sample: logger.fatal(\"Need sample name if not using config file\") sys.exit(1) if args.raw_bam or",
"if not using config file\") sys.exit(1) if args.raw_bam or args.proc_bam: assert not args.fq1,",
"True # global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s}",
"args.sample_cfg) sys.exit(1) if args.joint_calls: if len(samples)<2: logger.fatal(\"Need at least two samples for joint",
"#--- project specific imports # # add lib dir for this pipeline installation",
"= args.bam_only cfg_dict['gvcf_only'] = args.gvcf_only cfg_dict['hc_nct'] = args.hc_nct cfg_dict['joint_calls'] = args.joint_calls cfg_dict['interval_padding'] =",
"BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process up until GVCF file\") args = parser.parse_args()",
"dictionary with sample names as key (mostly just # one) and readunit keys",
"GVCF file\") args = parser.parse_args() # Repeateable -v and -q for setting logging",
"parser.add_argument('--proc-bam', help=\"Advanced: Injects processed (post-dedup, post-BQSR etc.) BAM (overwrites fq options).\" \" WARNING:",
"as value. readunits is a dict with # readunits (think: fastq pairs with",
"logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser = configargparse.ArgumentParser(description=__doc__.format(",
"-> WARNING # script -q -> ERROR # script -qq -> CRITICAL #",
"import yaml #--- project specific imports # # add lib dir for this",
"imports # import sys import os import logging #--- third-party imports # import",
"only dump() and following do not automatically create aliases yaml.Dumper.ignore_aliases = lambda *args:",
"and targeted sequencing.\") default = 4 parser.add_argument(\"-c\", \"--hc-nct\", default=default, type=int, help=\"Number of Haplotype",
"cfg_dict['mark_dups']: target += \".dedup\" if cfg_dict['seqtype'] != 'targeted': target += \".bqsr\" target +=",
"-v and -q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4",
"LIB_PATH) from readunits import get_samples_and_readunits_from_cfgfile from readunits import get_readunits_from_args from pipelines import get_pipeline_version",
"creates pipeline-specific config files to given output directory and runs the pipeline (unless",
"config file\") sys.exit(1) if args.seqtype in ['WES', 'targeted']: if not args.bed: logger.fatal(\"Analysis of",
"# global logger logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( '[{asctime}] {levelname:8s} {filename}",
"if len(samples)<2: logger.fatal(\"Need at least two samples for joint calling\") sys.exit(1) # turn",
"(\"BAM injection overwrites fastq arguments\") if args.raw_bam: assert os.path.exists(args.raw_bam) assert not args.proc_bam, (\"Cannot",
"calling\") sys.exit(1) # turn arguments into cfg_dict (gets merged with other configs late)",
"pipeline (unless otherwise requested). \"\"\" # generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while",
"\"out\", args.sample, \"{}.bwamem.bam\".format(args.sample)) os.makedirs(os.path.dirname(target)) os.symlink(os.path.abspath(args.raw_bam), target) src_bai = os.path.abspath(args.raw_bam) + \".bai\" if os.path.exists(src_bai):",
"and {PIPELINE_VERSION} replaced while # printing usage #--- standard library imports # import",
"well parser.add_argument('--bam-only', action='store_true', help=\"Only process up until BAM file\") parser.add_argument('--gvcf-only', action='store_true', help=\"Only process",
"import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"2016 Genome Institute",
"arguments.\" \" Use one or the other\") sys.exit(1) if not os.path.exists(args.sample_cfg): logger.fatal(\"Config file",
"logger.fatal(\"Need sample name if not using config file\") sys.exit(1) if args.raw_bam or args.proc_bam:",
"runs requires a bed file\") sys.exit(1) else: if not os.path.exists(args.bed): logger.fatal(\"Bed file %s",
"lib dir for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\",",
"{message}', style='{')) logger.addHandler(handler) def main(): \"\"\"main function \"\"\" default_parser = default_argparser(CFG_DIR, with_readunits=True) parser",
"# Repeateable -v and -q for setting logging level. # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/ #",
"if os.path.exists(args.outdir): logger.fatal(\"Output directory %s already exists\", args.outdir) sys.exit(1) # samples is a",
"pipelines import get_pipeline_version from pipelines import PipelineHandler from pipelines import logger as aux_logger",
"get_cluster_cfgfile from pipelines import default_argparser import configargparse __author__ = \"<NAME>\" __email__ = \"<EMAIL>\"",
"as folder name. also used for cluster job names PIPELINE_NAME = \"gatk\" MARK_DUPS",
"= readunits cfg_dict['samples'] = samples cfg_dict['seqtype'] = args.seqtype cfg_dict['intervals'] = os.path.abspath(args.bed) if args.bed",
"logger.fatal(\"Config file overrides fastq, sample and BAM arguments.\" \" Use one or the",
"readunits import get_readunits_from_args from pipelines import get_pipeline_version from pipelines import PipelineHandler from pipelines"
] |
[
"swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\":",
"}, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\",",
"Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded",
"\"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\"",
"\"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ],",
"Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\":",
"}, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish",
"\"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan",
"\"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ],",
"\"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\",",
"Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, {",
") chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\":",
"\"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" },",
"}, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\"",
"\"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id",
"\"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id )",
"Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\":",
"Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora",
"{ \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\":",
"Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, {",
"american = Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" },",
"Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\",",
"{ \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\"",
"{ \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\":",
"{ \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, {",
"\"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\":",
"\"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue",
"\"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id )",
"\"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id )",
") swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\",",
"\"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\":",
"aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced",
"Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\":",
"Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\":",
"\"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"},",
"{ \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" },",
"\"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean",
"db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit() def",
"= Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64",
"\"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\":",
") turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\",",
"\"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\",",
"\"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender",
"\"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese",
"\"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\":",
"\"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\":",
"\"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\":",
"{\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id )",
"\"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink",
"\"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\" }, {",
"\"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\":",
"], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" },",
"\"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\":",
"french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\":",
"}, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" },",
"}, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\",",
"Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion",
"\"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" },",
"{\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\":",
"from app.models import db, User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\":",
"\"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\"",
"\"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\",",
"}, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow',",
"\"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue",
"\"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow",
"{\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id )",
"{ \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City",
"{ \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\":",
"}, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american =",
"\"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green",
"{ \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\":",
"}, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\":",
"\"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish =",
"}, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle',",
"\"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian",
"{\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id )",
"Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, {",
"Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"},",
"\"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\",",
"{ \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\"",
"{ \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" },",
"\"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, {",
"\"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british",
"colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light",
"\"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ],",
"= Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\":",
"\"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" },",
"user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" },",
"Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\":",
"user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\":",
"Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\",",
"\"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ],",
"\"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch)",
"{\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\",",
"\"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, {",
"\"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ],",
"user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, {",
") german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange",
"{ \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[",
"= Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\",",
"\"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\",",
"\"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\",",
"\"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id",
"indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\":",
"{ \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, {",
"{ \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\"",
"Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id )",
"\"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\":",
"\"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\":",
"german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\",",
"\"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american)",
"\"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\",",
"colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\":",
"Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\":",
"\"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\":",
"\"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian)",
"app.models import db, User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\",",
"\"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\":",
"\"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\":",
"{ \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, {",
"= Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\":",
"\"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\":",
"canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"},",
"\"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"},",
"}, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\":",
"\"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\",",
"\"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ { \"name\":",
"}, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\"",
"user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german)",
"}, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\":",
"{\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\",",
"\"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\",",
"\"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh",
"\"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\":",
"\"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\",",
"\"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"},",
"\"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" },",
"db, User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"},",
"\"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\":",
") american = Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\"",
"\"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"},",
"seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\":",
"colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" },",
"Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\"",
"\"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"},",
"\"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ],",
"{\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\":",
"{ \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\"",
"}, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\":",
"\"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id )",
"def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\",",
"\"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\"",
"}, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british =",
"\"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ {",
"\"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id )",
"}, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\":",
"}, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch =",
"{ \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit",
"\"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\":",
"{ \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, {",
"\"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, {",
"Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\":",
"}, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" },",
"colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" },",
") indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, {",
"{ \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical',",
"\"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch',",
"\"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" },",
"\"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\"",
"\"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June",
"\"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\"",
"\"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\",",
"\"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie =",
"], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\"",
"Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\",",
"db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit() def undo_palettes(): db.session.execute('TRUNCATE",
"\"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[",
"Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\":",
"user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" },",
"colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\",",
"{\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\":",
"Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"},",
"\"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ],",
"user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" },",
"\"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\",",
"\"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid",
"\"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish =",
"colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\",",
"{ \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, {",
"\"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\",",
"\"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"},",
"}, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\":",
"\"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\":",
"\"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch",
"\"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\"",
"\"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\":",
"\"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, {",
"\"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\":",
"= Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, {",
"\"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british)",
"Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\":",
"{ \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\"",
"}, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\":",
"}, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\":",
"british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\",",
"user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty",
"Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\":",
"Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco",
"], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"},",
"{\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\",",
"{\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[",
"\"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\":",
"], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" },",
") db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish)",
"\"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\"",
"\"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[",
"\"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\"",
"\"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, {",
"\"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile",
"= Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"},",
"{\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\":",
"Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id )",
"}, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian =",
"\"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\",",
"Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ],",
"\"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ],",
"{\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\":",
"Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id",
"\"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\":",
"{\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\",",
"\"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\":",
"Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id",
"Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\":",
"= Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro",
"\"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" },",
"\"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey",
"\"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id",
"\"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french)",
"\"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german",
"\"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise",
"\"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, {",
"}, { \"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\":",
"Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, {",
"\"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ {",
"\"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling",
"\"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\":",
"\"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id )",
"Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese)",
"\"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\",",
"{\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\":",
") aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\":",
"user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\":",
"}, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\":",
"Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\":",
"\"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[",
"\"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea',",
"user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\":",
"\"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ {",
"\"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\":",
"\"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" },",
"Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright",
"}, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\"",
"colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\"",
"\"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, {",
"Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\":",
"{ \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\": \"#55E6C1\"",
"Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\":",
"\"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ { \"name\": \"Light",
"\"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\",",
"russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\",",
"\"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american",
"Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\":",
"= Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"},",
"], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" },",
"}, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\":",
"Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"},",
"{ \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\"",
"colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\",",
"Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\",",
"\"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer",
"Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\":",
"\"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id )",
"Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\":",
"= Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\",",
"{\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\":",
"\"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ],",
"], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\":",
"\"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\",",
"\"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\",",
"}, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\":",
") british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\":",
"{\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish)",
"{\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora', colors=[",
"user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" }, {",
"{\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\":",
"{\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\":",
"\"name\": \"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\"",
"{ \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" },",
"user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark",
"}, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish =",
"\"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id",
"colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" },",
"Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id",
"\"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" },",
"{ \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" },",
") dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\":",
"Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\":",
"}, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian =",
"\"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ {",
"\"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"},",
"{ \"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\"",
"\"name\": \"Pink Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\" },",
"}, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\":",
"\"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\":",
"Glamour\", \"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\":",
"\"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\":",
"db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit() def undo_palettes(): db.session.execute('TRUNCATE palettes;')",
"Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\"",
"\"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild",
"{\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\",",
"\"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ {",
"], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\":",
"\"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id )",
"\"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish",
"], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\"",
"}, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\", \"color\":",
"\"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\":",
"= Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\":",
"\"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\",",
"\"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\",",
"Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\":",
"{ \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral',",
"\"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian)",
"\"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\":",
"\"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\",",
"Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish",
"chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\",",
"\"Paradise Green\", \"color\": \"#b8e994\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ {",
"\"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\":",
"\"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy",
"\"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty",
"}, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" },",
"Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"},",
"\"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\":",
"\"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, {",
"Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\":",
"\"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" },",
"\"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights',",
"{ \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, {",
"\"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep",
"user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, {",
"db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit() def undo_palettes(): db.session.execute('TRUNCATE palettes;') db.session.commit()",
"\"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\":",
"\"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, {",
"\"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat",
") russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy",
"{ \"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\"",
"\"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" },",
"\"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" },",
"\"color\": \"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet",
"\"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\",",
"}, ], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\":",
"\"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id",
"\"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie",
"= Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\":",
"{ \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" },",
"\"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed",
"db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish)",
"\"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese =",
"{\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\",",
"Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[ { \"name\": \"Red\",",
"Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\":",
"\"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner",
"Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"},",
"\"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\":",
"turkish = Palette(title='Desert', colors=[ {\"name\": \"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\":",
"\"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ],",
"\"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\":",
"}, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\"",
"\"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id",
"Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id",
"\"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, {",
"{ \"name\": \"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\"",
"\"#575fcf\"}, {\"name\": \"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\",",
"{ \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" },",
"}, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\"",
"Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german =",
"\"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora Bora',",
"\"#25CCF7\" }, { \"name\": \"Honey Glow\", \"color\": \"#EAB543\" }, { \"name\": \"Sweet Garden\",",
"}, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\"",
"Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\", \"color\": \"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\":",
"Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\":",
"\"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[",
"\"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\": \"Old",
"import db, User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\":",
"\"Megaman\", \"color\": \"#4bcffa\"}, {\"name\": \"Fresh Turquoise\", \"color\": \"#34e7e4\"}, {\"name\": \"Minty Green\", \"color\": \"#0be881\"},",
"\"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\", \"color\": \"#ff7979\" },",
"\"color\": \"#9C27B0\" }, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\",",
"{\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id",
"\"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\":",
"{\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish",
"\"<NAME>\", \"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\",",
"\"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"},",
"\"#00a8ff\" }, { \"name\": \"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\"",
"}, { \"name\": \"Deep Purple\", \"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\"",
"Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\":",
"\"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum",
"\"color\": \"#e77f67\"}, {\"name\": \"Old Geranium\", \"color\": \"#cf6a87\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) german = Palette(title='Bora",
"\"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\":",
"Orange\", \"color\": \"#FEA47F\" }, { \"name\": \"Spiro Disco Ball\", \"color\": \"#25CCF7\" }, {",
"\"color\": \"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french",
"}, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" },",
"], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"},",
"\"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\":",
"db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit() def undo_palettes():",
"colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"}, {\"name\": \"Dark Periwinkle\", \"color\": \"#575fcf\"}, {\"name\": \"Megaman\",",
"}, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" }, { \"name\": \"Green Darner Tail\",",
"colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, { \"name\": \"<NAME>\", \"color\": \"#f8c291\"",
"Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\":",
"\"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\",",
"\"Coastal Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[",
"\"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\",",
"User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\":",
"\"Periwinkle\", \"color\": \"#9c88ff\" }, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download",
"\"#ffaf40\"}, {\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[",
"}, { \"name\": \"Download Progress\", \"color\": \"#4cd137\" }, { \"name\": \"Seabrook\", \"color\": \"#487eb0\"",
"{ \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\": \"C64 Purple\", \"color\": \"#706fd3\"",
"{ \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\"",
"\"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter Pink\", \"color\": \"#ef5777\"},",
"\"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\":",
") spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, {",
"{ \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\": \"Purple\", \"color\": \"#9C27B0\" }, {",
"\"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[",
"{ \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" },",
"db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian) db.session.add(german) db.session.add(turkish) db.session.add(swedish) db.session.commit()",
"dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\",",
"\"Swan White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, {",
"Green\", \"color\": \"#0be881\"}, ], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie)",
"\"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\":",
"\"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\":",
"Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\":",
"\"color\": \"#f8c291\" }, { \"name\": \"Livid\", \"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\":",
"], user_id=User.query.filter_by(username='Demo').first().id ) indian = Palette(title='Tropical', colors=[ { \"name\": \"Orchid Orange\", \"color\": \"#FEA47F\"",
"\"#ff6b6b\"}, {\"name\": \"Megaman\", \"color\": \"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id",
"{ \"name\": \"Seabrook\", \"color\": \"#487eb0\" }, ], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[",
"\"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\", \"color\": \"#b8e994\" }, ],",
"], user_id=User.query.filter_by(username='cow').first().id ) aussie = Palette(title='Jungle', colors=[ { \"name\": \"Beekeeper\", \"color\": \"#f6e58d\" },",
"\"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\" }, { \"name\":",
"\"color\": \"#ff7979\" }, { \"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal",
"\"name\": \"June Bud\", \"color\": \"#badc58\" }, { \"name\": \"Coastal Breeze\", \"color\": \"#dff9fb\" },",
") french = Palette(title='Rainbow', colors=[ { \"name\": \"Flat Flesh\", \"color\": \"#fad390\" }, {",
"Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"},",
"{ \"name\": \"Energos\", \"color\": \"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" },",
"Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\": \"#E91E63\"",
"\"#48dbfb\"}, {\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium',",
"\"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\": \"Highlighter",
"Palette(title='Metalics', colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel",
"\"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial",
"\"#673AB7\" }, { \"name\": \"indigo\", \"color\": \"#3F51B5\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) french =",
"\"name\": \"C64 Purple\", \"color\": \"#706fd3\" }, { \"name\": \"Swan White\", \"color\": \"#f7f1e3\" },",
"\"#C4E538\" }, { \"name\": \"Blue Martina\", \"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\",",
"Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\": \"#ff4d4d\"}, {\"name\": \"<NAME>\", \"color\": \"#ffaf40\"}, {\"name\":",
"\"Falling Star\", \"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ {",
"= Palette(title='Chromium', colors=[ { \"name\": \"Red\", \"color\": \"#F44336\" }, { \"name\": \"Pink\", \"color\":",
"\"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\",",
"{ \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels',",
"\"color\": \"#f7d794\"}, {\"name\": \"Soft Blue\", \"color\": \"#778beb\"}, {\"name\": \"Brewed Mustard\", \"color\": \"#e77f67\"}, {\"name\":",
"\"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\",",
"], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ { \"name\": \"Light Greenish Blue\",",
"colors=[ {\"name\": \"Jigglypuff\", \"color\": \"#ff9ff3\"}, {\"name\": \"Casandora Yellow\", \"color\": \"#feca57\"}, {\"name\": \"Pastel Red\",",
"], user_id=User.query.filter_by(username='bob').first().id ) db.session.add(canadian) db.session.add(chinese) db.session.add(french) db.session.add(indian) db.session.add(spanish) db.session.add(british) db.session.add(aussie) db.session.add(american) db.session.add(dutch) db.session.add(russian)",
"colors=[ {\"name\": \"Creamy Peach\", \"color\": \"#f3a683\"}, {\"name\": \"Rosy Highlight\", \"color\": \"#f7d794\"}, {\"name\": \"Soft",
"spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons Purple\", \"color\": \"#40407a\" }, { \"name\":",
"= Palette(title='Primrose', colors=[ { \"name\": \"Sunflower\", \"color\": \"#FFC312\" }, { \"name\": \"Energos\", \"color\":",
"\"Light Greenish Blue\", \"color\": \"#55efc4\" }, { \"name\": \"Faded Poster\", \"color\": \"#81ecec\" },",
"\"Bright Lilac\", \"color\": \"#cd84f1\"}, {\"name\": \"Pretty Please\", \"color\": \"#ffcccc\"}, {\"name\": \"Light Red\", \"color\":",
"\"#FDA7DF\" }, { \"name\": \"Bara Rose\", \"color\": \"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian",
"{\"name\": \"Unmellow Yellow\", \"color\": \"#fffa65\"}, ], user_id=User.query.filter_by(username='saad').first().id ) swedish = Palette(title='Ikea', colors=[ {\"name\":",
"{\"name\": \"Wild Caribbean Green\", \"color\": \"#1dd1a1\"}, ], user_id=User.query.filter_by(username='monkey').first().id ) chinese = Palette(title='Chromium', colors=[",
"\"#81ecec\" }, { \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy",
"\"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\": \"Pink Glamour\",",
"\"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" }, ],",
"White\", \"color\": \"#f7f1e3\" }, { \"name\": \"Summer Sky\", \"color\": \"#34ace0\" }, { \"name\":",
"\"color\": \"#12CBC4\" }, { \"name\": \"Lavender Rose\", \"color\": \"#FDA7DF\" }, { \"name\": \"Bara",
"\"#ED4C67\" }, ], user_id=User.query.filter_by(username='saad').first().id ) russian = Palette(title='Fruit Punch', colors=[ {\"name\": \"Creamy Peach\",",
"\"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"}, ], user_id=User.query.filter_by(username='Demo').first().id ) turkish = Palette(title='Desert',",
"\"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"}, {\"name\": \"Maximum Blue Green\", \"color\": \"#2bcbba\"},",
"Breeze\", \"color\": \"#dff9fb\" }, ], user_id=User.query.filter_by(username='monkey').first().id ) american = Palette(title='City Lights', colors=[ {",
"\"color\": \"#CAD3C8\" }, ], user_id=User.query.filter_by(username='saad').first().id ) spanish = Palette(title='Floral', colors=[ { \"name\": \"Jacksons",
"{ \"name\": \"City Lights\", \"color\": \"#dfe6e9\" }, ], user_id=User.query.filter_by(username='Demo').first().id ) dutch = Palette(title='Primrose',",
"\"color\": \"#6a89cc\" }, { \"name\": \"Spray\", \"color\": \"#82ccdd\" }, { \"name\": \"Paradise Green\",",
"<filename>backend/app/seeds/palettes.py from app.models import db, User, Palette def seed_palettes(): canadian = Palette(title='Metalics', colors=[",
"\"name\": \"Sweet Garden\", \"color\": \"#55E6C1\" }, { \"name\": \"Falling Star\", \"color\": \"#CAD3C8\" },",
"}, { \"name\": \"Rise-N-Shine\", \"color\": \"#fbc531\" }, { \"name\": \"Download Progress\", \"color\": \"#4cd137\"",
"\"Orange Hibiscus\", \"color\": \"#fd9644\"}, {\"name\": \"Flirtatious\", \"color\": \"#fed330\"}, {\"name\": \"Reptile Green\", \"color\": \"#26de81\"},",
"user_id=User.query.filter_by(username='bob').first().id ) british = Palette(title='Pastels', colors=[ { \"name\": \"<NAME>\", \"color\": \"#00a8ff\" }, {",
"\"Beekeeper\", \"color\": \"#f6e58d\" }, { \"name\": \"Spiced Nectarine\", \"color\": \"#ffbe76\" }, { \"name\":",
"\"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\": \"#a29bfe\" }, { \"name\": \"City",
"{ \"name\": \"Green Darner Tail\", \"color\": \"#74b9ff\" }, { \"name\": \"Shy Moment\", \"color\":",
"Sky\", \"color\": \"#34ace0\" }, { \"name\": \"Celestial Green\", \"color\": \"#33d9b2\" }, ], user_id=User.query.filter_by(username='bob').first().id",
"Palette(title='Bora Bora', colors=[ {\"name\": \"Fusion Red\", \"color\": \"#fc5c65\"}, {\"name\": \"Orange Hibiscus\", \"color\": \"#fd9644\"},"
] |
[
"it out.') return False return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder =",
"method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with",
"= 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name",
"station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala'",
"= method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to",
"= compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) != 2:",
"station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container:",
"None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output = dict()",
"method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title]",
"def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is None) or (month is",
"2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter],",
"self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name,",
"run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for variable_name in self.variables_of_interest: variable =",
"ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward =",
"parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time,",
"cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa:",
"%(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self,",
"['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name",
"year, month = read_year_month_config() if station_names is None: single_stations = read_single_stations_config() self.station_links =",
"perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data",
"logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1,",
"continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters)",
"philosophy of these definitions also suck (ye ye ye ye I am completely",
"' + self.process_name) logger.info('Has processes defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The",
"+ str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables ' + str(self.variables_of_interest)) def",
"new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1,",
"len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to the QC methods",
"utils import * from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__)",
"not exist. Will not use this station.') def assign_qc_processes(self): # TODO: also get",
"netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s",
"I should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002']",
"(year is None) or (month is None): year, month = read_year_month_config() if station_names",
"def process_stations(self): for station in self.station_container: logger.info('Processing station ' + station.name + '...')",
"found. Will pop it out.') return False return True def run_through_variables_of_interest(self): variable_counter =",
"if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name]",
"link, name, year, month): # TODO: fix converted_time1 plz self.year = year self.month",
"= method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect",
"import * from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter",
"cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect",
"self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters)",
"station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name",
"logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s",
"station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name",
"cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar:",
"were connected with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name]",
"'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name =",
"return False return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for",
"= compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name])",
"var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name =",
"np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1",
"= get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time",
"tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year,",
"cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif",
"set.\") return qc_counter = 0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if",
"self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] =",
"input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not enough",
"is None): year, month = read_year_month_config() if station_names is None: single_stations = read_single_stations_config()",
"input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) qc_counter +=",
"%(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager:",
"be necessarily be here.... ! # Btw, the philosophy of these definitions also",
"not use this station.') def assign_qc_processes(self): # TODO: also get dat stuff from",
"for station ' + name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + '",
"self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None",
"method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to the",
"defined for this station: ' + cur_name + '. Will use default now.')",
"logger.info('Processing station ' + station.name + '...') station.perform_qc() logger.info('Plotting and saving station '",
"method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name)",
"variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def",
"= 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup =",
"Btw, the philosophy of these definitions also suck (ye ye ye ye I",
"really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001']",
"= self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions",
"cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined",
"variable_name + ' not found. Will pop it out.') return False return True",
"respect to the QC methods set.\") return qc_counter = 0 for qc_method in",
"cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else:",
"if qc_method == 'range': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue",
"plz self.year = year self.month = month self.link = link self.name = name",
"been assigned to the process ' + self.process_name) logger.info('Has processes defined for the",
"= [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information()",
"method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if",
"qc_counter = 0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method ==",
"variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx =",
"self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) !=",
"= self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0])",
"get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions = qc_definitions",
"self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable",
"self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions =",
"self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays()",
"__init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is None) or (month is None):",
"logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name]",
"meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in",
"is None) or (month is None): year, month = read_year_month_config() if station_names is",
"station in self.station_container: logger.info('Processing station ' + station.name + '...') station.perform_qc() logger.info('Plotting and",
"len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1],",
"compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) !=",
"meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011']",
"<filename>Station.py from utils import * from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger",
"self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source link",
"read_year_month_config() if station_names is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month,",
"cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not enough input",
"+ station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + ' finished.')",
"station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name +",
"' not found. Will pop it out.') return False return True def run_through_variables_of_interest(self):",
"= get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station ' + name) self.station_container.append(Station(link, name,",
"hardcoded # and I should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008']",
"logger.error(\"Incorrect amount of flags with respect to the QC methods set.\") return qc_counter",
"= None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output =",
"= np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data,",
"cur_name + '. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name",
"to the process ' + self.process_name) logger.info('Has processes defined for the variables '",
"self.link) logger.info('Has been assigned to the process ' + self.process_name) logger.info('Has processes defined",
"qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in",
"ye ye I am completely aware that they are hardcoded # and I",
"station.') def assign_qc_processes(self): # TODO: also get dat stuff from database goddamn it",
"station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing station '",
"connected with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except",
"= self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing station ' +",
"self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---')",
"= ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name",
"return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for variable_name in",
"translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions",
"in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition",
"the philosophy of these definitions also suck (ye ye ye ye I am",
"station_names is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year",
"station_names=None): if (year is None) or (month is None): year, month = read_year_month_config()",
"= compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters)",
"'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in",
"= method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables",
"logger.info('Provided by source link ' + self.link) logger.info('Has been assigned to the process",
"for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters)",
"if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data,",
"Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name]",
"self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable =",
"elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name]",
"+ cur_name + '. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name =",
"self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest = []",
"self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self):",
"or (month is None): year, month = read_year_month_config() if station_names is None: single_stations",
"for link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data",
"' does not exist. Will not use this station.') def assign_qc_processes(self): # TODO:",
"logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d",
"suck (ye ye ye ye I am completely aware that they are hardcoded",
"get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time =",
"diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name in",
"- %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO)",
"'. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions =",
"in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No",
"for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward",
"QC methods set.\") return qc_counter = 0 for qc_method in cur_qc_methods: input_parameters =",
"and saving station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' +",
"they are hardcoded # and I should have really avoided that) axys_watchMate_meteo =",
"= self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods)",
"map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest =",
"' + variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0]",
"cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name =",
"station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station: ' + cur_name",
"input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not",
"+ ' does not exist. Will not use this station.') def assign_qc_processes(self): #",
"cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station: ' +",
"for station in self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name =",
"axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in",
"self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self): for link in",
"only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions = qc_definitions self.station_container = []",
"logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler",
"except IndexError: logger.warning('Variable of interest ' + variable_name + ' not found. Will",
"interest ' + variable_name + ' not found. Will pop it out.') return",
"logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif",
"that they are hardcoded # and I should have really avoided that) axys_watchMate_meteo",
"check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest ' + variable_name +",
"%(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler)",
"self.process_name = '' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest",
"qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue #",
"by source link ' + self.link) logger.info('Has been assigned to the process '",
"from utils import * from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger =",
"== 'range': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] =",
"variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of",
"meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process",
"= cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing",
"= read_year_month_config() if station_names is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year,",
"name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts)",
"!= len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to the QC methods set.\")",
"self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station '",
"fix converted_time1 plz self.year = year self.month = month self.link = link self.name",
"get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions =",
"== 'gradient': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name]",
"def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest ' + variable_name",
"qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name]",
"single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month",
"self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time]",
"self.year, self.month)) else: logger.info(link + ' does not exist. Will not use this",
"+ '. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions",
"station.log_station_information() def create_stations(self): for link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/',",
"with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError:",
"in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name",
"logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method",
"else: logger.info(link + ' does not exist. Will not use this station.') def",
"also get dat stuff from database goddamn it # TODO: outsource dat here,",
"qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) !=",
"station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing station ' + station.name +",
"str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self,",
"StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is None) or (month",
"TODO: outsource dat here, should not be necessarily be here.... ! # Btw,",
"outsource dat here, should not be necessarily be here.... ! # Btw, the",
"month=None, station_names=None): if (year is None) or (month is None): year, month =",
"dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not",
"Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in",
"= map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest",
"necessarily be here.... ! # Btw, the philosophy of these definitions also suck",
"qc_method == 'range': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name]",
"[] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information() def",
"self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time)",
"self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self): for",
"year=None, month=None, station_names=None): if (year is None) or (month is None): year, month",
"' finished.') class Station: def __init__(self, link, name, year, month): # TODO: fix",
"+ station.name + ' finished.') class Station: def __init__(self, link, name, year, month):",
"logger.warning('Variable of interest ' + variable_name + ' not found. Will pop it",
"be here.... ! # Btw, the philosophy of these definitions also suck (ye",
"class Station: def __init__(self, link, name, year, month): # TODO: fix converted_time1 plz",
"self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] =",
"date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda",
"= logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter)",
"input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not",
"not found. Will pop it out.') return False return True def run_through_variables_of_interest(self): variable_counter",
"in self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name]",
"= method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name)",
"= np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods",
"Station: def __init__(self, link, name, year, month): # TODO: fix converted_time1 plz self.year",
"in self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name",
"= logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if",
"Will pop it out.') return False return True def run_through_variables_of_interest(self): variable_counter = 0",
"am completely aware that they are hardcoded # and I should have really",
"name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + ' does not exist. Will",
"station in self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links: if check_link_availability(link): name",
"translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest = []",
"'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo:",
"dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name =",
"is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year =",
"from database goddamn it # TODO: outsource dat here, should not be necessarily",
"= ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container:",
"'...') station.perform_qc() logger.info('Plotting and saving station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing",
"= self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station: ' + cur_name +",
"= year self.month = month self.link = link self.name = name self.root =",
"!= 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name])",
"it # TODO: outsource dat here, should not be necessarily be here.... !",
"+ str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest '",
"- %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class",
"station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name",
"self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/',",
"in self.station_container: logger.info('Processing station ' + station.name + '...') station.perform_qc() logger.info('Plotting and saving",
"' + self.link) logger.info('Has been assigned to the process ' + self.process_name) logger.info('Has",
"'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this",
"TODO: fix converted_time1 plz self.year = year self.month = month self.link = link",
"station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa'",
"name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station ' + name) self.station_container.append(Station(link,",
"defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the",
"variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables ' +",
"of interest ' + variable_name + ' not found. Will pop it out.')",
"if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to the QC",
"in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station",
"in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp,",
"out.') return False return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = []",
"input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) != 2: logger.error('Not enough",
"ye I am completely aware that they are hardcoded # and I should",
"= 0 tab_holder = [] for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable",
"+ name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + ' does not exist.",
"= cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name",
"len(input_parameters) != 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter],",
"log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source link ' + self.link)",
"self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source link '",
"handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None,",
"month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self):",
"logger.warning('No Process defined for this station: ' + cur_name + '. Will use",
"cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup):",
"exist. Will not use this station.') def assign_qc_processes(self): # TODO: also get dat",
"self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) != 2:",
"cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) != 2: logger.error('Not",
"meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in",
"False return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for variable_name",
"[] for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data =",
"= get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions =",
"self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station: ' + cur_name + '.",
"pop it out.') return False return True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder",
"input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method",
"month = read_year_month_config() if station_names is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html',",
"self.station_container: logger.info('Processing station ' + station.name + '...') station.perform_qc() logger.info('Plotting and saving station",
"and I should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa =",
"station.perform_qc() logger.info('Plotting and saving station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station",
"not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self):",
"logger.info('Processing station ' + station.name + ' finished.') class Station: def __init__(self, link,",
"0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if",
"self.month)) else: logger.info(link + ' does not exist. Will not use this station.')",
"elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name]",
"- %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def",
"continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if",
"qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name]",
"if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def",
"= '' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest =",
"get dat stuff from database goddamn it # TODO: outsource dat here, should",
"handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None):",
"year self.month = month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations()",
"= [] self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition",
"self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx))",
"1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif",
"self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter],",
"# and I should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa",
"qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for",
"else: logger.warning('No Process defined for this station: ' + cur_name + '. Will",
"= self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data,",
"variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9",
"str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest ' +",
"return qc_counter = 0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method",
"= np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter +=",
"'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name =",
"+ self.link) logger.info('Has been assigned to the process ' + self.process_name) logger.info('Has processes",
"def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source link ' +",
"in self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links: if check_link_availability(link): name =",
"['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station",
"get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data !=",
"input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not enough",
"for station in self.station_container: logger.info('Processing station ' + station.name + '...') station.perform_qc() logger.info('Plotting",
"print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links: if",
"self.process_name) logger.info('Has processes defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were",
"== 'spike': if len(input_parameters) != 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] =",
"link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for",
"!= 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter],",
"now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self):",
"self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions",
"= read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month =",
"for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name)",
"self.name, self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name)",
"goddamn it # TODO: outsource dat here, should not be necessarily be here....",
"len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0],",
"!= 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1],",
"self.name) logger.info('Provided by source link ' + self.link) logger.info('Has been assigned to the",
"None): year, month = read_year_month_config() if station_names is None: single_stations = read_single_stations_config() self.station_links",
"Process defined for this station: ' + cur_name + '. Will use default",
"# TODO: also get dat stuff from database goddamn it # TODO: outsource",
"check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station ' + name)",
"parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) qc_counter += 1",
"compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not",
"station ' + name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + ' does",
"for this station: ' + cur_name + '. Will use default now.') cur_process_name",
"(ye ye ye ye I am completely aware that they are hardcoded #",
"these definitions also suck (ye ye ye ye I am completely aware that",
"method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount",
"get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue",
"= [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x:",
"def assign_qc_processes(self): # TODO: also get dat stuff from database goddamn it #",
"cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not enough input",
"logger.info('Has processes defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected",
"' + cur_name + '. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name",
"continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station",
"+ '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + ' finished.') class Station:",
"= ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004',",
"link) logger.info('Found data for station ' + name) self.station_container.append(Station(link, name, self.year, self.month)) else:",
"definitions were connected with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try:",
"self.link = link self.name = name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time",
"__init__(self, link, name, year, month): # TODO: fix converted_time1 plz self.year = year",
"+ ' not found. Will pop it out.') return False return True def",
"self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self):",
"x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest =",
"are hardcoded # and I should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010',",
"[] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for",
"self.qc_output[variable_name]) elif qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not enough input parameters.')",
"class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is None) or",
"= Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts",
"(month is None): year, month = read_year_month_config() if station_names is None: single_stations =",
"completely aware that they are hardcoded # and I should have really avoided",
"also suck (ye ye ye ye I am completely aware that they are",
"if len(input_parameters) != 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0],",
"'spike': if len(input_parameters) != 1: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data,",
"avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar",
"difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter",
"station.name + ' finished.') class Station: def __init__(self, link, name, year, month): #",
"['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name if",
"the QC methods set.\") return qc_counter = 0 for qc_method in cur_qc_methods: input_parameters",
"logger.info('Found data for station ' + name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link",
"in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name",
"logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s -",
"= ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for",
"should have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala",
"= get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1",
"self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup",
"def print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links:",
"elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name]",
"parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient': if",
"= cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name",
"here.... ! # Btw, the philosophy of these definitions also suck (ye ye",
"['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005',",
"qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1,",
"logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source link ' + self.link) logger.info('Has",
"this station.') def assign_qc_processes(self): # TODO: also get dat stuff from database goddamn",
"self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for",
"with respect to the QC methods set.\") return qc_counter = 0 for qc_method",
"the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables '",
"logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s -",
"station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar'",
"compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif",
"cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method ==",
"amount of flags with respect to the QC methods set.\") return qc_counter =",
"the process ' + self.process_name) logger.info('Has processes defined for the variables ' +",
"here, should not be necessarily be here.... ! # Btw, the philosophy of",
"[] self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition in",
"' + self.name) logger.info('Provided by source link ' + self.link) logger.info('Has been assigned",
"new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data,",
"2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name])",
"of these definitions also suck (ye ye ye ye I am completely aware",
"station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + ' finished.') class",
"= link self.name = name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time =",
"get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx",
"formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S')",
"for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data =",
"self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' +",
"self.month = month self.link = link self.name = name self.root = Dataset(link) self.time",
"= 0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range':",
"that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar =",
"' + station.name + ' finished.') class Station: def __init__(self, link, name, year,",
"self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container:",
"' + name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + ' does not",
"'gradient': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] =",
"new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name",
"self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not enough input parameters.')",
"if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time,",
"name, year, month): # TODO: fix converted_time1 plz self.year = year self.month =",
"link ' + self.link) logger.info('Has been assigned to the process ' + self.process_name)",
"station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + ' finished.') class Station: def __init__(self,",
"self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable)",
"elif qc_method == 'gradient': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue",
"variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) #",
"self.root[variable_name] except IndexError: logger.warning('Variable of interest ' + variable_name + ' not found.",
"year self.month = month self.link = link self.name = name self.root = Dataset(link)",
"= month self.link = link self.name = name self.root = Dataset(link) self.time =",
"tab_holder = [] for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]]",
"cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala:",
"cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) != 2: logger.error('Not enough input parameters.')",
"= month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def",
"from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s]",
"meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name =",
"+ ' finished.') class Station: def __init__(self, link, name, year, month): # TODO:",
"if station_names is None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations)",
"= 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name",
"use this station.') def assign_qc_processes(self): # TODO: also get dat stuff from database",
"enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] =",
"len(input_parameters) != 2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1],",
"self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing station ' + station.name",
"self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted)",
"for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable)",
"converted_time1 plz self.year = year self.month = month self.link = link self.name =",
"self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data",
"= self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions =",
"self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items():",
"Will not use this station.') def assign_qc_processes(self): # TODO: also get dat stuff",
"= self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions",
"variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest:",
"import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d",
"variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data",
"= dict() self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name",
"[datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime())",
"= name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted =",
"= get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name]",
"station.name + '...') station.perform_qc() logger.info('Plotting and saving station ' + station.name + '...')",
"month self.link = link self.name = name self.root = Dataset(link) self.time = get_data_array(self.root['time'])",
"variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data =",
"True def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for variable_name in self.variables_of_interest:",
"= self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data",
"' + variable_name + ' not found. Will pop it out.') return False",
"input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data,",
"'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012', 'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003',",
"= self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by source",
"0 tab_holder = [] for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable =",
"'%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions,",
"dat here, should not be necessarily be here.... ! # Btw, the philosophy",
"self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not enough input parameters.')",
"= year self.month = month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes()",
"self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output",
"have really avoided that) axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala =",
"!= new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder,",
"this station: ' + cur_name + '. Will use default now.') cur_process_name =",
"p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler =",
"= get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name =",
"+ self.name) logger.info('Provided by source link ' + self.link) logger.info('Has been assigned to",
"+= 1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing",
"= 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name",
"year, month): # TODO: fix converted_time1 plz self.year = year self.month = month",
"logger.info('Plotting and saving station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station '",
"month, only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions = qc_definitions self.station_container =",
"IndexError: logger.warning('Variable of interest ' + variable_name + ' not found. Will pop",
"cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not enough input",
"aware that they are hardcoded # and I should have really avoided that)",
"self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name",
"import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s",
"self.year = year self.month = month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations()",
"self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if",
"station ' + station.name + '...') station.perform_qc() logger.info('Plotting and saving station ' +",
"# Btw, the philosophy of these definitions also suck (ye ye ye ye",
"elif qc_method == 'spike': if len(input_parameters) != 1: logger.error('Not enough input parameters.') continue",
"if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station ' +",
"= self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions",
"len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0]",
"%H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None,",
"'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name",
"def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name]",
"station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions =",
"in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name",
"use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest()",
"self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] = method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station '",
"= 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station",
"new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name,",
"saving station ' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name",
"= logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d - %(name)s - %(levelname)s - %(message)s',",
"read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year self.month = month",
"to the QC methods set.\") return qc_counter = 0 for qc_method in cur_qc_methods:",
"len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable, self.converted_time_backward,",
"assigned to the process ' + self.process_name) logger.info('Has processes defined for the variables",
"np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods =",
"logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is None)",
"variable_counter = 0 tab_holder = [] for variable_name in self.variables_of_interest: variable = self.root[variable_name]",
"name, self.year, self.month)) else: logger.info(link + ' does not exist. Will not use",
"logger.info(link + ' does not exist. Will not use this station.') def assign_qc_processes(self):",
"' + station.name + '...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + '",
"logger.info('The definitions were connected with the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name):",
"qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx =",
"stuff from database goddamn it # TODO: outsource dat here, should not be",
"process ' + self.process_name) logger.info('Has processes defined for the variables ' + str(self.process_definitions.method_container.keys()))",
"variable_data, variable, self.converted_time_backward, qc_data=qc_variable_data, new_qc_data=new_qc_variable_data, diff_idx=difference_highlights_idx)) variable_counter += 1 plot_bokeh(tab_holder, self.name, self.year, self.month)",
"self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) !=",
"qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided by",
"1 plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing '",
"= dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if",
"self.month = month self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information()",
"self.name = name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted",
"= get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions",
"= [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output = dict() def get_defined_variables_of_interest(self):",
"= cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) != 2: logger.error('Not enough input",
"'station_parcbit-scb_met004', 'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name if cur_name",
"None) or (month is None): year, month = read_year_month_config() if station_names is None:",
"+ station.name + '...') station.perform_qc() logger.info('Plotting and saving station ' + station.name +",
"elif qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue",
"link self.name = name self.root = Dataset(link) self.time = get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time)",
"self.process_stations() self.print_station_information() def print_station_information(self): for station in self.station_container: station.log_station_information() def create_stations(self): for link",
"process_stations(self): for station in self.station_container: logger.info('Processing station ' + station.name + '...') station.perform_qc()",
"+ variable_name + ' not found. Will pop it out.') return False return",
"year, month, only_single_stations=single_stations) self.year = year self.month = month self.qc_definitions = qc_definitions self.station_container",
"' + station.name + '...') station.perform_qc() logger.info('Plotting and saving station ' + station.name",
"should not be necessarily be here.... ! # Btw, the philosophy of these",
"cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name",
"cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of",
"axys_watchMate_meteo = ['buoy_canaldeibiza-scb_met010', 'buoy_bahiadepalma-scb_met008'] meteoStation_aanderaa = ['station_salines-ime_met002'] meteoStation_vaisala = ['mobims_calamillor-scb_met001'] meteoStation_vaisala_airp_mbar = ['mobims_playadepalma-scb_met012',",
"! # Btw, the philosophy of these definitions also suck (ye ye ye",
"!= 2: logger.error('Not enough input parameters.') continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter],",
"station: ' + cur_name + '. Will use default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar'",
"station in self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo'",
"= [] for variable_name in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data",
"= self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx]",
"self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions =",
"cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for station in self.station_container: logger.info('Processing station",
"# TODO: fix converted_time1 plz self.year = year self.month = month self.link =",
"= cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station: '",
"default now.') cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def",
"nan_idx = np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters",
"for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables",
"data for station ' + name) self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link +",
"= np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters =",
"self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data = get_data_array(qc_variable) # new_qc_variable_data =",
"' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest",
"plot_bokeh(tab_holder, self.name, self.year, self.month) def perform_qc(self): for variable_name in self.variables_of_interest: logger.info('Processing ' +",
"parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike':",
"meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in",
"logger.info('Has been assigned to the process ' + self.process_name) logger.info('Has processes defined for",
"not be necessarily be here.... ! # Btw, the philosophy of these definitions",
"methods set.\") return qc_counter = 0 for qc_method in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter]",
"if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0],",
"qc_definitions, year=None, month=None, station_names=None): if (year is None) or (month is None): year,",
"get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = ''",
"get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found data for station ' + name) self.station_container.append(Station(link, name, self.year,",
"= get_data_array(qc_variable) # new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data",
"2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name])",
"self.qc_output = dict() def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title",
"cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name =",
"= qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for station",
"def get_defined_variables_of_interest(self): for method_name, method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name):",
"'/L1/', link) logger.info('Found data for station ' + name) self.station_container.append(Station(link, name, self.year, self.month))",
"= station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions",
"method_definition qc_variable_name = self.root[var_name].ancillary_variables self.qc_variables_of_interest.append(qc_variable_name) def log_station_information(self): logger.info('---') logger.info('Station ' + self.name) logger.info('Provided",
"station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for this station:",
"# new_qc_variable_data = np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0]",
"len(cur_qc_lookup): logger.error(\"Incorrect amount of flags with respect to the QC methods set.\") return",
"assign_qc_processes(self): # TODO: also get dat stuff from database goddamn it # TODO:",
"self.station_container: cur_name = station.name if cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name =",
"for station in self.station_container: station.log_station_information() def create_stations(self): for link in self.station_links: if check_link_availability(link):",
"continue # self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1],",
"+ '...') station.perform_qc() logger.info('Plotting and saving station ' + station.name + '...') station.run_through_variables_of_interest()",
"logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name])",
"def create_stations(self): for link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link)",
"%(lineno)d - %(name)s - %(levelname)s - %(message)s', '%m-%d %H:%M:%S') handler.setFormatter(formatter) handler = logging.FileHandler('station.log')",
"'station_galfi-scb_met005', 'station_esporles-scb_met003', 'mobims_sonbou-scb_met011'] for station in self.station_container: cur_name = station.name if cur_name in",
"+ variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx",
"# self.qc_output[variable_name] = compute_simple_gradient(variable_data, input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0],",
"= cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name = 'MeteoStation_Aanderaa' station.process_name",
"'' self.process_definitions = None self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict()",
"'range': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data,",
"compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) != 1:",
"cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name =",
"definitions also suck (ye ye ye ye I am completely aware that they",
"def run_through_variables_of_interest(self): variable_counter = 0 tab_holder = [] for variable_name in self.variables_of_interest: variable",
"input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method ==",
"database goddamn it # TODO: outsource dat here, should not be necessarily be",
"does not exist. Will not use this station.') def assign_qc_processes(self): # TODO: also",
"self.converted_time1 = get_pandas_timestamp_series(date_converted) translate_time = self.converted_time1.apply(lambda x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name",
"' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with the variables ' + str(self.variables_of_interest))",
"'stationary': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data,",
"self.variables_of_interest = [] self.qc_variables_of_interest = [] self.definitions_of_interest = dict() self.qc_output = dict() def",
"np.asarray(np.ones((1, len(qc_variable_data)))[0]) new_qc_variable_data = self.qc_output[variable_name] difference_highlights_idx = np.where(qc_variable_data != new_qc_variable_data)[0] tab_holder.append(get_bokeh_tab(self.converted_time1, variable_data, variable,",
"variable = self.root[variable_name] variable_data = get_data_array(variable) self.qc_output[variable_name] = np.ones((1, len(variable_data)))[0] nan_idx = np.isnan(variable_data)",
"create_stations(self): for link in self.station_links: if check_link_availability(link): name = get_station_name_from_link('weather_station/', '/L1/', link) logger.info('Found",
"input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary': if len(input_parameters) != 2: logger.error('Not enough",
"method_definition in self.process_definitions.method_container.items(): var_name = method_definition.title if not self.check_variable_existence(var_name): continue self.variables_of_interest.append(var_name) self.definitions_of_interest[method_definition.title] =",
"variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable of interest ' + variable_name + '",
"enough input parameters.') continue self.qc_output[variable_name] = compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method",
"self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_vaisala_airp_mbar: cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions =",
"ye ye ye I am completely aware that they are hardcoded # and",
"enough input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method ==",
"= compute_valid_range(variable_data, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'spike': if len(input_parameters) !=",
"in cur_qc_methods: input_parameters = cur_qc_input_parameters[qc_counter] if qc_method == 'range': if len(input_parameters) != 2:",
"cur_name in meteoStation_vaisala: cur_process_name = 'MeteoStation_Vaisala' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif",
"station ' + station.name + ' finished.') class Station: def __init__(self, link, name,",
"finished.') class Station: def __init__(self, link, name, year, month): # TODO: fix converted_time1",
"# TODO: outsource dat here, should not be necessarily be here.... ! #",
"source link ' + self.link) logger.info('Has been assigned to the process ' +",
"variable_name in self.variables_of_interest: logger.info('Processing ' + variable_name) variable = self.root[variable_name] variable_data = get_data_array(variable)",
"'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif cur_name in meteoStation_aanderaa: cur_process_name =",
"I am completely aware that they are hardcoded # and I should have",
"input parameters.') continue self.qc_output[variable_name] = compute_spike(variable_data, input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'gradient':",
"if (year is None) or (month is None): year, month = read_year_month_config() if",
"self.station_container.append(Station(link, name, self.year, self.month)) else: logger.info(link + ' does not exist. Will not",
"the variables ' + str(self.variables_of_interest)) def check_variable_existence(self, variable_name): try: self.root[variable_name] except IndexError: logger.warning('Variable",
"self.year = year self.month = month self.link = link self.name = name self.root",
"* from netCDF4 import Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter =",
"None: single_stations = read_single_stations_config() self.station_links = get_mooring_stations('http://thredds.socib.es/thredds/catalog/mooring/weather_station/catalog.html', year, month, only_single_stations=single_stations) self.year = year",
"9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1] cur_qc_lookup = method_definitions[2]",
"of flags with respect to the QC methods set.\") return qc_counter = 0",
"self.qc_output[variable_name]) self.qc_output[variable_name] = compute_extended_gradient(variable_data, self.time, input_parameters[1], input_parameters[0], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) elif qc_method == 'stationary':",
"TODO: also get dat stuff from database goddamn it # TODO: outsource dat",
"logger.info('Station ' + self.name) logger.info('Provided by source link ' + self.link) logger.info('Has been",
"handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year is",
"cur_process_name = 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] station.get_defined_variables_of_interest() def process_stations(self): for",
"processes defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions were connected with",
"np.isnan(variable_data) self.qc_output[variable_name][nan_idx] = 9 method_definitions = self.definitions_of_interest[variable_name].get_method_arrays() cur_qc_methods = method_definitions[0] cur_qc_input_parameters = method_definitions[1]",
"def __init__(self, link, name, year, month): # TODO: fix converted_time1 plz self.year =",
"self.qc_definitions = qc_definitions self.station_container = [] self.create_stations() self.assign_qc_processes() self.process_stations() self.print_station_information() def print_station_information(self): for",
"x: x.to_pydatetime()) self.converted_time_backward = map(totimestamp, translate_time) self.process_name = '' self.process_definitions = None self.variables_of_interest",
"+ self.process_name) logger.info('Has processes defined for the variables ' + str(self.process_definitions.method_container.keys())) logger.info('The definitions",
"month): # TODO: fix converted_time1 plz self.year = year self.month = month self.link",
"dat stuff from database goddamn it # TODO: outsource dat here, should not",
"== 'stationary': if len(input_parameters) != 2: logger.error('Not enough input parameters.') continue self.qc_output[variable_name] =",
"'...') station.run_through_variables_of_interest() logger.info('Processing station ' + station.name + ' finished.') class Station: def",
"Dataset import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s] p%(process)s %(lineno)d -",
"cur_name in axys_watchMate_meteo: cur_process_name = 'Axys_WatchMate_Meteo' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] elif",
"= method_definitions[1] cur_qc_lookup = method_definitions[2] if len(cur_qc_methods) != len(cur_qc_lookup): logger.error(\"Incorrect amount of flags",
"get_data_array(self.root['time']) self.converted_time = get_md_datenum(self.time) date_converted = [datetime.fromtimestamp(ts) for ts in self.time] self.converted_time1 =",
"= 'MeteoStation_Vaisala_Airp_Mbar' station.process_name = cur_process_name station.process_definitions = self.qc_definitions.processes[cur_process_name] else: logger.warning('No Process defined for",
"enough input parameters.') continue self.qc_output[variable_name] = compute_stationary(variable_data, self.time, input_parameters[0], input_parameters[1], cur_qc_lookup[qc_counter], self.qc_output[variable_name]) qc_counter",
"logging.FileHandler('station.log') handler.setLevel(logging.INFO) logger.addHandler(handler) class StationManager: def __init__(self, qc_definitions, year=None, month=None, station_names=None): if (year",
"flags with respect to the QC methods set.\") return qc_counter = 0 for",
"try: self.root[variable_name] except IndexError: logger.warning('Variable of interest ' + variable_name + ' not",
"in self.variables_of_interest: variable = self.root[variable_name] qc_variable = self.root[self.qc_variables_of_interest[variable_counter]] variable_data = get_data_array(variable) qc_variable_data ="
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"bvals file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image",
"output file location of the B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti,",
"KIND, either express or implied. # See the License for the specific language",
"= ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to extract B0 from",
"Unless required by applicable law or agreed to in writing, software # distributed",
"permissions and # limitations under the License. # # extract_b0.py # Created by",
"under the License. # # extract_b0.py # Created by <NAME> on 2015-02-21. #",
"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 # #",
"argparse import ArgumentParser from nibabel import load, save, Nifti1Image from numpy import where,",
"parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to extract B0",
"loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\"",
"\"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating",
"Open Connectome Project (http://openconnecto.me) # # Licensed under the Apache License, Version 2.0",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"b-value file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file",
"compliance with the License. # You may obtain a copy of the License",
"# Copyright 2015 Open Connectome Project (http://openconnecto.me) # # Licensed under the Apache",
"help=\"The output file location of the B0 scan (.nii, .nii.gz)\") result = parser.parse_args()",
"# Created by <NAME> on 2015-02-21. # Email: <EMAIL> # Copyright (c) 2015.",
"load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\" b =",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"ArgumentParser from nibabel import load, save, Nifti1Image from numpy import where, loadtxt def",
"dti data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading",
"language governing permissions and # limitations under the License. # # extract_b0.py #",
"d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting",
"numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"Email: <EMAIL> # Copyright (c) 2015. All rights reserved. from argparse import ArgumentParser",
"(c) 2015. All rights reserved. from argparse import ArgumentParser from nibabel import load,",
"you may not use this file except in compliance with the License. #",
"bvals, b0_vol): print \"Loading dti data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"<EMAIL> # Copyright (c) 2015. All rights reserved. from argparse import ArgumentParser from",
"b0_head = d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting B0",
"(.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the DTI image (.b)\")",
"(.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the B0 scan (.nii, .nii.gz)\")",
"ANY KIND, either express or implied. # See the License for the specific",
"License. # # extract_b0.py # Created by <NAME> on 2015-02-21. # Email: <EMAIL>",
"header=b0_head ) save(out, b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\",",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"the License. # # extract_b0.py # Created by <NAME> on 2015-02-21. # Email:",
"action=\"store\", help=\"The output file location of the B0 scan (.nii, .nii.gz)\") result =",
"nibabel import load, save, Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img, bvals,",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def main(): parser =",
"rights reserved. from argparse import ArgumentParser from nibabel import load, save, Nifti1Image from",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol)",
"not use this file except in compliance with the License. # You may",
"data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"<NAME> on 2015-02-21. # Email: <EMAIL> # Copyright (c) 2015. All rights reserved.",
"DTI image we want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"= d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals) print",
"print \"Loading dti data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header()",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"import load, save, Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol):",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img =",
"2015-02-21. # Email: <EMAIL> # Copyright (c) 2015. All rights reserved. from argparse",
"\"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def",
"to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to",
"file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location",
"corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of",
"print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\"",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"action=\"store\", help=\"The DTI image we want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\",",
"= Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def main(): parser",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"\"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want",
"of the B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0) if",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"Project (http://openconnecto.me) # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"2015. All rights reserved. from argparse import ArgumentParser from nibabel import load, save,",
"reserved. from argparse import ArgumentParser from nibabel import load, save, Nifti1Image from numpy",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the B0 scan (.nii,",
"help=\"The b-value file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output",
"from nibabel import load, save, Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img,",
"OF ANY KIND, either express or implied. # See the License for the",
"extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img = load(dti_img) b0_data = d_img.get_data()",
"Copyright 2015 Open Connectome Project (http://openconnecto.me) # # Licensed under the Apache License,",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"\"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out =",
"\"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head )",
"main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to extract",
"# you may not use this file except in compliance with the License.",
"import ArgumentParser from nibabel import load, save, Nifti1Image from numpy import where, loadtxt",
"save, Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading",
"b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals)",
"for the specific language governing permissions and # limitations under the License. #",
"agreed to in writing, software # distributed under the License is distributed on",
"extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the",
"B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0) if __name__ ==",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"# # extract_b0.py # Created by <NAME> on 2015-02-21. # Email: <EMAIL> #",
"def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img = load(dti_img) b0_data =",
"save(out, b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI",
"from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the DTI image",
"(the \"License\"); # you may not use this file except in compliance with",
"limitations under the License. # # extract_b0.py # Created by <NAME> on 2015-02-21.",
"where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img = load(dti_img)",
"parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to extract B0 from (.nii, .nii.gz)\")",
"# # Unless required by applicable law or agreed to in writing, software",
"ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to extract B0 from (.nii,",
"def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we want to",
"express or implied. # See the License for the specific language governing permissions",
"parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\",",
"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",
"b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print",
"the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the B0",
"by applicable law or agreed to in writing, software # distributed under the",
"2015 Open Connectome Project (http://openconnecto.me) # # Licensed under the Apache License, Version",
"print \"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print",
".nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\",",
"to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"action=\"store\", help=\"The b-value file corresponding to the DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The",
"file location of the B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals,",
"either express or implied. # See the License for the specific language governing",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"# limitations under the License. # # extract_b0.py # Created by <NAME> on",
"# Email: <EMAIL> # Copyright (c) 2015. All rights reserved. from argparse import",
"# 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",
"load, save, Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print",
"DTI image (.b)\") parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the B0 scan",
"# extract_b0.py # Created by <NAME> on 2015-02-21. # Email: <EMAIL> # Copyright",
"Connectome Project (http://openconnecto.me) # # Licensed under the Apache License, Version 2.0 (the",
"extract_b0.py # Created by <NAME> on 2015-02-21. # Email: <EMAIL> # Copyright (c)",
"parser.add_argument(\"b0\", action=\"store\", help=\"The output file location of the B0 scan (.nii, .nii.gz)\") result",
"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",
"\"Loading dti data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print",
"b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image",
"file except in compliance with the License. # You may obtain a copy",
"and # limitations under the License. # # extract_b0.py # Created by <NAME>",
"from numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\"",
"b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(),",
"Created by <NAME> on 2015-02-21. # Email: <EMAIL> # Copyright (c) 2015. All",
"= load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\" b",
"B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding to the DTI",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License for the specific language governing permissions and # limitations under the License.",
"d_img = load(dti_img) b0_data = d_img.get_data() b0_head = d_img.get_header() print \"Loading bvals file...\"",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])]",
"on 2015-02-21. # Email: <EMAIL> # Copyright (c) 2015. All rights reserved. from",
"the License. # You may obtain a copy of the License at #",
"Copyright (c) 2015. All rights reserved. from argparse import ArgumentParser from nibabel import",
"specific language governing permissions and # limitations under the License. # # extract_b0.py",
"Nifti1Image from numpy import where, loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti",
") save(out, b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The",
"to in writing, software # distributed under the License is distributed on an",
"by <NAME> on 2015-02-21. # Email: <EMAIL> # Copyright (c) 2015. All rights",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\"",
"(.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0) if __name__ == \"__main__\": main()",
"the specific language governing permissions and # limitations under the License. # #",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"= loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print",
"\"License\"); # you may not use this file except in compliance with the",
"we want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"required by applicable law or agreed to in writing, software # distributed under",
"location of the B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0)",
"b0_vol): print \"Loading dti data...\" d_img = load(dti_img) b0_data = d_img.get_data() b0_head =",
"applicable law or agreed to in writing, software # distributed under the License",
"# Copyright (c) 2015. All rights reserved. from argparse import ArgumentParser from nibabel",
"print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head",
"volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data,",
"image we want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value",
"out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def main():",
"or agreed to in writing, software # distributed under the License is distributed",
"affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\",",
"or implied. # See the License for the specific language governing permissions and",
"from argparse import ArgumentParser from nibabel import load, save, Nifti1Image from numpy import",
"print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out",
"#!/usr/bin/env python # Copyright 2015 Open Connectome Project (http://openconnecto.me) # # Licensed under",
"B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image(",
"help=\"The DTI image we want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\",",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"All rights reserved. from argparse import ArgumentParser from nibabel import load, save, Nifti1Image",
"image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3]) print \"Saving...\" out = Nifti1Image( data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out,",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"print \"Complete!\" def main(): parser = ArgumentParser(description=\"\") parser.add_argument(\"dti\", action=\"store\", help=\"The DTI image we",
"loadtxt def extract_vol(dti_img, bvals, b0_vol): print \"Loading dti data...\" d_img = load(dti_img) b0_data",
"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 # #",
"b = loadtxt(bvals) print \"Extracting B0 volume...\" b0_data=b0_data[:,:,:,int(where(b==0)[0])] print \"Updating image header...\" b0_head.set_data_shape(b0_head.get_data_shape()[0:3])",
"= d_img.get_header() print \"Loading bvals file...\" b = loadtxt(bvals) print \"Extracting B0 volume...\"",
"scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0) if __name__ == \"__main__\":",
"with the License. # You may obtain a copy of the License at",
"(http://openconnecto.me) # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"governing permissions and # limitations under the License. # # extract_b0.py # Created",
"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",
"want to extract B0 from (.nii, .nii.gz)\") parser.add_argument(\"bvals\", action=\"store\", help=\"The b-value file corresponding",
"the B0 scan (.nii, .nii.gz)\") result = parser.parse_args() extract_vol(result.dti, result.bvals, result.b0) if __name__",
"data=b0_data, affine=d_img.get_affine(), header=b0_head ) save(out, b0_vol) print \"Complete!\" def main(): parser = ArgumentParser(description=\"\")",
"python # Copyright 2015 Open Connectome Project (http://openconnecto.me) # # Licensed under the",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[
"^ as an up arrow \"\"\" # TODO: works, but needs cleanup from",
"native API) A two-segment snake slithers aimlessly over the display. On intersections, the",
"WildSnakePy - WildSnakeUNO ported to Galileo (mraa native API) A two-segment snake slithers",
"str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head choices = moves[head] if",
"middle segment going right, the code is 6, going left in the same",
"code is 6, going left in the same place is code 13. >:0",
"F G SEGMENTS = 7 pins = [8, 9, 10, 11, 12, 13,",
"% str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head choices = moves[head]",
"8, 7, 6, 12, 13}; # DojoXXG # A B G E D",
"- WildSnakeUNO ported to Galileo (mraa native API) A two-segment snake slithers aimlessly",
"[1, -1], # 0 [13, 2], # 1 [3, -1], # 2 [4,",
"# 10 [10, -1], # 11 [6, 11], # 12 [5, 11] #",
"the snake head is at the middle segment going right, the code is",
"[ [1, -1], # 0 [13, 2], # 1 [3, -1], # 2",
"SEGMENTS = 7 pins = [8, 9, 10, 11, 12, 13, 7] display",
"random.choice([0,1]) print ' choice ' + str(choice) head = choices[choice] print 'setup()' setup()",
"moves[head] if (choices[1] == -1) : head = choices[0] # no second choice",
"<filename>galileo/WildSnakePy/WildSnake.py \"\"\" WildSnakePy - WildSnakeUNO ported to Galileo (mraa native API) A two-segment",
"second choice else: choice = random.choice([0,1]) print ' choice ' + str(choice) head",
"steps for each current position and direction. Snake head position and direction is",
"----- \"\"\" # A B C D E F G #int display[] =",
"B C D E F G SEGMENTS = 7 pins = [8, 9,",
"read: > as a right arrow < as a left arrow v as",
"display[tail % 7].write(1) #MRAA def loop(): global head global tail print ' head",
"tail ' + str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read() print 'delay",
"F #int display[] = {8, 9, 7, 12, 11, 10, 7, 13}; #",
"choice ' + str(choice) head = choices[choice] print 'setup()' setup() print 'loop()' while",
"v:11 | | ^:9 ----- <:3 >:10 To understand this diagram, read: >",
"logic is encoded in the `moves` array which lists possible next steps for",
"13 ] print moves \"\"\" A ----- F | | B | G",
"%pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA def",
"-1) : head = choices[0] # no second choice else: choice = random.choice([0,1])",
"11], # 12 [5, 11] # 13 ] print moves \"\"\" A -----",
"global tail print ' head ' + str(head%7) print ' tail ' +",
"pot = Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i])",
"works, but needs cleanup from mraa import * import time, random # {first_choice,",
"11, 10, 7, 13}; # A B C D E F G SEGMENTS",
"% 7].write(0) #MRAA tail = head choices = moves[head] if (choices[1] == -1)",
"7, 12, 11, 10, 7, 13}; # A B C D E F",
"below, i.e. when the snake head is at the middle segment going right,",
"# 11 [6, 11], # 12 [5, 11] # 13 ] print moves",
"9, 7, 12, 11, 10, 7, 13}; # A B C D E",
"# segment B tail = 9 # segment A pot = Aio(0) def",
"= [Gpio(i) for i in pins] print repr(display) head = 8 # segment",
"E F G #int display[] = {11, 10, 8, 7, 6, 12, 13};",
"' + str(choice) head = choices[choice] print 'setup()' setup() print 'loop()' while True:",
"as a left arrow v as a down arrow ^ as an up",
"= 9 # segment A pot = Aio(0) def setup(): for i in",
"B tail = 9 # segment A pot = Aio(0) def setup(): for",
"-1], # 2 [4, -1], # 3 [6, 5], # 4 [0, -1],",
"== -1) : head = choices[0] # no second choice else: choice =",
"time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head choices = moves[head] if (choices[1]",
"direction. Snake head position and direction is coded like pictured below, i.e. when",
"ported to Galileo (mraa native API) A two-segment snake slithers aimlessly over the",
"the same place is code 13. >:0 <:7 ----- ^:5 | | v:1",
"' tail ' + str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read() print",
"next step is chosen at random. Most of the logic is encoded in",
"B C D E F G #int display[] = {11, 10, 8, 7,",
"over the display. On intersections, the next step is chosen at random. Most",
"[10, -1], # 11 [6, 11], # 12 [5, 11] # 13 ]",
"-1], # 8 [13, 8], # 9 [9, -1], # 10 [10, -1],",
"# * -1 means there is no second_choice moves = [ [1, -1],",
": head = choices[0] # no second choice else: choice = random.choice([0,1]) print",
"moves \"\"\" A ----- F | | B | G | ----- E",
"A B G E D C G F #int display[] = {8, 9,",
"Galileo (mraa native API) A two-segment snake slithers aimlessly over the display. On",
"13}; # DojoXXG # A B G E D C G F #int",
"TODO: works, but needs cleanup from mraa import * import time, random #",
"# TODO: works, but needs cleanup from mraa import * import time, random",
"str(head%7) print ' tail ' + str(tail%7) display[head % 7].write(1) #MRAA delay =",
"%d' %pins[i] display[tail % 7].write(1) #MRAA def loop(): global head global tail print",
"-1], # 5 [2, 8], # 6 [12, -1], # 7 [7, -1],",
"7, 13}; # A B C D E F G SEGMENTS = 7",
"| v:1 v:12 | >:6 | ^:8 ----- ^:4 | <:13| v:2 v:11",
"intersections, the next step is chosen at random. Most of the logic is",
">:6 | ^:8 ----- ^:4 | <:13| v:2 v:11 | | ^:9 -----",
"display[] = {8, 9, 7, 12, 11, 10, 7, 13}; # A B",
"----- <:3 >:10 To understand this diagram, read: > as a right arrow",
"| D | ----- \"\"\" # A B C D E F G",
"5], # 4 [0, -1], # 5 [2, 8], # 6 [12, -1],",
"of the logic is encoded in the `moves` array which lists possible next",
"%s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head choices =",
"# 3 [6, 5], # 4 [0, -1], # 5 [2, 8], #",
"in pins] print repr(display) head = 8 # segment B tail = 9",
"A two-segment snake slithers aimlessly over the display. On intersections, the next step",
"-1], # 10 [10, -1], # 11 [6, 11], # 12 [5, 11]",
"10, 8, 7, 6, 12, 13}; # DojoXXG # A B G E",
"i %d' %pins[i] display[tail % 7].write(1) #MRAA def loop(): global head global tail",
"F G #int display[] = {11, 10, 8, 7, 6, 12, 13}; #",
"at random. Most of the logic is encoded in the `moves` array which",
"^:9 ----- <:3 >:10 To understand this diagram, read: > as a right",
"----- F | | B | G | ----- E | | C",
"* import time, random # {first_choice, second_choice*} # * -1 means there is",
"[2, 8], # 6 [12, -1], # 7 [7, -1], # 8 [13,",
"print moves \"\"\" A ----- F | | B | G | -----",
"\"\"\" # A B C D E F G #int display[] = {11,",
"^:8 ----- ^:4 | <:13| v:2 v:11 | | ^:9 ----- <:3 >:10",
"8], # 9 [9, -1], # 10 [10, -1], # 11 [6, 11],",
"segment A pot = Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA",
"needs cleanup from mraa import * import time, random # {first_choice, second_choice*} #",
"a right arrow < as a left arrow v as a down arrow",
"def loop(): global head global tail print ' head ' + str(head%7) print",
"pictured below, i.e. when the snake head is at the middle segment going",
"going right, the code is 6, going left in the same place is",
"second_choice*} # * -1 means there is no second_choice moves = [ [1,",
"9, 10, 11, 12, 13, 7] display = [Gpio(i) for i in pins]",
"= 8 # segment B tail = 9 # segment A pot =",
"# DojoXXG # A B G E D C G F #int display[]",
"7 [7, -1], # 8 [13, 8], # 9 [9, -1], # 10",
"= Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1)",
"a down arrow ^ as an up arrow \"\"\" # TODO: works, but",
"tail = 9 # segment A pot = Aio(0) def setup(): for i",
"display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i]",
"if (choices[1] == -1) : head = choices[0] # no second choice else:",
"\"\"\" A ----- F | | B | G | ----- E |",
"'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail %",
"# A B C D E F G #int display[] = {11, 10,",
"def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin",
"v:2 v:11 | | ^:9 ----- <:3 >:10 To understand this diagram, read:",
"slithers aimlessly over the display. On intersections, the next step is chosen at",
"# {first_choice, second_choice*} # * -1 means there is no second_choice moves =",
"right arrow < as a left arrow v as a down arrow ^",
"10, 11, 12, 13, 7] display = [Gpio(i) for i in pins] print",
"repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d'",
"-1], # 3 [6, 5], # 4 [0, -1], # 5 [2, 8],",
"13. >:0 <:7 ----- ^:5 | | v:1 v:12 | >:6 | ^:8",
"6, going left in the same place is code 13. >:0 <:7 -----",
"Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print",
"head ' + str(head%7) print ' tail ' + str(tail%7) display[head % 7].write(1)",
"head choices = moves[head] if (choices[1] == -1) : head = choices[0] #",
"^:4 | <:13| v:2 v:11 | | ^:9 ----- <:3 >:10 To understand",
"right, the code is 6, going left in the same place is code",
"D C G F #int display[] = {8, 9, 7, 12, 11, 10,",
"same place is code 13. >:0 <:7 ----- ^:5 | | v:1 v:12",
"step is chosen at random. Most of the logic is encoded in the",
"A B C D E F G #int display[] = {11, 10, 8,",
"display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print",
"head = choices[0] # no second choice else: choice = random.choice([0,1]) print '",
"print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head",
"each current position and direction. Snake head position and direction is coded like",
"repr(display) head = 8 # segment B tail = 9 # segment A",
"E F G SEGMENTS = 7 pins = [8, 9, 10, 11, 12,",
"diagram, read: > as a right arrow < as a left arrow v",
"random # {first_choice, second_choice*} # * -1 means there is no second_choice moves",
"import time, random # {first_choice, second_choice*} # * -1 means there is no",
"# 7 [7, -1], # 8 [13, 8], # 9 [9, -1], #",
"G F #int display[] = {8, 9, 7, 12, 11, 10, 7, 13};",
"#int display[] = {11, 10, 8, 7, 6, 12, 13}; # DojoXXG #",
"# 1 [3, -1], # 2 [4, -1], # 3 [6, 5], #",
"= pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail",
"| ^:8 ----- ^:4 | <:13| v:2 v:11 | | ^:9 ----- <:3",
"2], # 1 [3, -1], # 2 [4, -1], # 3 [6, 5],",
"11] # 13 ] print moves \"\"\" A ----- F | | B",
"head position and direction is coded like pictured below, i.e. when the snake",
"#MRAA print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested",
"= {11, 10, 8, 7, 6, 12, 13}; # DojoXXG # A B",
"pins] print repr(display) head = 8 # segment B tail = 9 #",
"v as a down arrow ^ as an up arrow \"\"\" # TODO:",
"----- ^:5 | | v:1 v:12 | >:6 | ^:8 ----- ^:4 |",
"to Galileo (mraa native API) A two-segment snake slithers aimlessly over the display.",
"tail print ' head ' + str(head%7) print ' tail ' + str(tail%7)",
"#int display[] = {8, 9, 7, 12, 11, 10, 7, 13}; # A",
"the next step is chosen at random. Most of the logic is encoded",
"place is code 13. >:0 <:7 ----- ^:5 | | v:1 v:12 |",
"the logic is encoded in the `moves` array which lists possible next steps",
"display[i].write(0) print 'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA def loop(): global",
"current position and direction. Snake head position and direction is coded like pictured",
"8 [13, 8], # 9 [9, -1], # 10 [10, -1], # 11",
"11, 12, 13, 7] display = [Gpio(i) for i in pins] print repr(display)",
"{first_choice, second_choice*} # * -1 means there is no second_choice moves = [",
"and direction. Snake head position and direction is coded like pictured below, i.e.",
"in the `moves` array which lists possible next steps for each current position",
"2 [4, -1], # 3 [6, 5], # 4 [0, -1], # 5",
"print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i",
"# segment A pot = Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT)",
"#MRAA def loop(): global head global tail print ' head ' + str(head%7)",
"C D E F G SEGMENTS = 7 pins = [8, 9, 10,",
"# 2 [4, -1], # 3 [6, 5], # 4 [0, -1], #",
"time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA def loop():",
"#MRAA tail = head choices = moves[head] if (choices[1] == -1) : head",
"' head ' + str(head%7) print ' tail ' + str(tail%7) display[head %",
"----- ^:4 | <:13| v:2 v:11 | | ^:9 ----- <:3 >:10 To",
"head = 8 # segment B tail = 9 # segment A pot",
"for i in pins] print repr(display) head = 8 # segment B tail",
"#MRAA delay = pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0)",
"12, 11, 10, 7, 13}; # A B C D E F G",
"5 [2, 8], # 6 [12, -1], # 7 [7, -1], # 8",
">:10 To understand this diagram, read: > as a right arrow < as",
"tail = head choices = moves[head] if (choices[1] == -1) : head =",
"for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d on'",
"direction is coded like pictured below, i.e. when the snake head is at",
"choice = random.choice([0,1]) print ' choice ' + str(choice) head = choices[choice] print",
"1 [3, -1], # 2 [4, -1], # 3 [6, 5], # 4",
"segment going right, the code is 6, going left in the same place",
"a left arrow v as a down arrow ^ as an up arrow",
"8], # 6 [12, -1], # 7 [7, -1], # 8 [13, 8],",
"<:13| v:2 v:11 | | ^:9 ----- <:3 >:10 To understand this diagram,",
"12, 13, 7] display = [Gpio(i) for i in pins] print repr(display) head",
"On intersections, the next step is chosen at random. Most of the logic",
"but needs cleanup from mraa import * import time, random # {first_choice, second_choice*}",
"-1], # 11 [6, 11], # 12 [5, 11] # 13 ] print",
"E D C G F #int display[] = {8, 9, 7, 12, 11,",
"global head global tail print ' head ' + str(head%7) print ' tail",
"is chosen at random. Most of the logic is encoded in the `moves`",
"in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2)",
"# 12 [5, 11] # 13 ] print moves \"\"\" A ----- F",
"6 [12, -1], # 7 [7, -1], # 8 [13, 8], # 9",
"the `moves` array which lists possible next steps for each current position and",
"10 [10, -1], # 11 [6, 11], # 12 [5, 11] # 13",
"<:7 ----- ^:5 | | v:1 v:12 | >:6 | ^:8 ----- ^:4",
"| C | D | ----- \"\"\" # A B C D E",
"encoded in the `moves` array which lists possible next steps for each current",
"# 8 [13, 8], # 9 [9, -1], # 10 [10, -1], #",
"understand this diagram, read: > as a right arrow < as a left",
"is no second_choice moves = [ [1, -1], # 0 [13, 2], #",
"lists possible next steps for each current position and direction. Snake head position",
">:0 <:7 ----- ^:5 | | v:1 v:12 | >:6 | ^:8 -----",
"C | D | ----- \"\"\" # A B C D E F",
"-1 means there is no second_choice moves = [ [1, -1], # 0",
"API) A two-segment snake slithers aimlessly over the display. On intersections, the next",
"coded like pictured below, i.e. when the snake head is at the middle",
"mraa import * import time, random # {first_choice, second_choice*} # * -1 means",
"# 0 [13, 2], # 1 [3, -1], # 2 [4, -1], #",
"| G | ----- E | | C | D | ----- \"\"\"",
"display. On intersections, the next step is chosen at random. Most of the",
"%d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail % 7].write(1)",
"12, 13}; # DojoXXG # A B G E D C G F",
"= 7 pins = [8, 9, 10, 11, 12, 13, 7] display =",
"display = [Gpio(i) for i in pins] print repr(display) head = 8 #",
"D E F G #int display[] = {11, 10, 8, 7, 6, 12,",
"| <:13| v:2 v:11 | | ^:9 ----- <:3 >:10 To understand this",
"A pot = Aio(0) def setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print",
"random. Most of the logic is encoded in the `moves` array which lists",
"# no second choice else: choice = random.choice([0,1]) print ' choice ' +",
"time, random # {first_choice, second_choice*} # * -1 means there is no second_choice",
"an up arrow \"\"\" # TODO: works, but needs cleanup from mraa import",
"' choice ' + str(choice) head = choices[choice] print 'setup()' setup() print 'loop()'",
"which lists possible next steps for each current position and direction. Snake head",
"`moves` array which lists possible next steps for each current position and direction.",
"cleanup from mraa import * import time, random # {first_choice, second_choice*} # *",
"C G F #int display[] = {8, 9, 7, 12, 11, 10, 7,",
"G | ----- E | | C | D | ----- \"\"\" #",
"segment B tail = 9 # segment A pot = Aio(0) def setup():",
"7].write(0) #MRAA tail = head choices = moves[head] if (choices[1] == -1) :",
"# A B C D E F G SEGMENTS = 7 pins =",
"choices[0] # no second choice else: choice = random.choice([0,1]) print ' choice '",
"<:3 >:10 To understand this diagram, read: > as a right arrow <",
"| | B | G | ----- E | | C | D",
"' + str(head%7) print ' tail ' + str(tail%7) display[head % 7].write(1) #MRAA",
"is at the middle segment going right, the code is 6, going left",
"# A B G E D C G F #int display[] = {8,",
"like pictured below, i.e. when the snake head is at the middle segment",
"print ' head ' + str(head%7) print ' tail ' + str(tail%7) display[head",
"str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read() print 'delay %s' % str(delay)",
"7, 6, 12, 13}; # DojoXXG # A B G E D C",
"13}; # A B C D E F G SEGMENTS = 7 pins",
"is coded like pictured below, i.e. when the snake head is at the",
"= {8, 9, 7, 12, 11, 10, 7, 13}; # A B C",
"left in the same place is code 13. >:0 <:7 ----- ^:5 |",
"two-segment snake slithers aimlessly over the display. On intersections, the next step is",
"head global tail print ' head ' + str(head%7) print ' tail '",
"the middle segment going right, the code is 6, going left in the",
"i.e. when the snake head is at the middle segment going right, the",
"# 5 [2, 8], # 6 [12, -1], # 7 [7, -1], #",
"(mraa native API) A two-segment snake slithers aimlessly over the display. On intersections,",
"G SEGMENTS = 7 pins = [8, 9, 10, 11, 12, 13, 7]",
"# 4 [0, -1], # 5 [2, 8], # 6 [12, -1], #",
"i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i]",
"loop(): global head global tail print ' head ' + str(head%7) print '",
"going left in the same place is code 13. >:0 <:7 ----- ^:5",
"on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA",
"10, 7, 13}; # A B C D E F G SEGMENTS =",
"print ' choice ' + str(choice) head = choices[choice] print 'setup()' setup() print",
"| ^:9 ----- <:3 >:10 To understand this diagram, read: > as a",
"there is no second_choice moves = [ [1, -1], # 0 [13, 2],",
"[3, -1], # 2 [4, -1], # 3 [6, 5], # 4 [0,",
"as a down arrow ^ as an up arrow \"\"\" # TODO: works,",
"9 # segment A pot = Aio(0) def setup(): for i in range(SEGMENTS):",
"v:1 v:12 | >:6 | ^:8 ----- ^:4 | <:13| v:2 v:11 |",
"[5, 11] # 13 ] print moves \"\"\" A ----- F | |",
"B G E D C G F #int display[] = {8, 9, 7,",
"arrow ^ as an up arrow \"\"\" # TODO: works, but needs cleanup",
"snake head is at the middle segment going right, the code is 6,",
"= [ [1, -1], # 0 [13, 2], # 1 [3, -1], #",
"for each current position and direction. Snake head position and direction is coded",
"display[tail % 7].write(0) #MRAA tail = head choices = moves[head] if (choices[1] ==",
"means there is no second_choice moves = [ [1, -1], # 0 [13,",
"the code is 6, going left in the same place is code 13.",
"\"\"\" # TODO: works, but needs cleanup from mraa import * import time,",
"0 [13, 2], # 1 [3, -1], # 2 [4, -1], # 3",
"6, 12, 13}; # DojoXXG # A B G E D C G",
"> as a right arrow < as a left arrow v as a",
"7].write(1) #MRAA delay = pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail %",
"G E D C G F #int display[] = {8, 9, 7, 12,",
"aimlessly over the display. On intersections, the next step is chosen at random.",
"as a right arrow < as a left arrow v as a down",
"= head choices = moves[head] if (choices[1] == -1) : head = choices[0]",
"pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail =",
"[9, -1], # 10 [10, -1], # 11 [6, 11], # 12 [5,",
"3 [6, 5], # 4 [0, -1], # 5 [2, 8], # 6",
"arrow < as a left arrow v as a down arrow ^ as",
"else: choice = random.choice([0,1]) print ' choice ' + str(choice) head = choices[choice]",
"no second_choice moves = [ [1, -1], # 0 [13, 2], # 1",
"print 'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA def loop(): global head",
"position and direction is coded like pictured below, i.e. when the snake head",
"| | v:1 v:12 | >:6 | ^:8 ----- ^:4 | <:13| v:2",
"[7, -1], # 8 [13, 8], # 9 [9, -1], # 10 [10,",
"< as a left arrow v as a down arrow ^ as an",
"+ str(head%7) print ' tail ' + str(tail%7) display[head % 7].write(1) #MRAA delay",
"DojoXXG # A B G E D C G F #int display[] =",
"| ----- E | | C | D | ----- \"\"\" # A",
"7] display = [Gpio(i) for i in pins] print repr(display) head = 8",
"i in pins] print repr(display) head = 8 # segment B tail =",
"up arrow \"\"\" # TODO: works, but needs cleanup from mraa import *",
"display[] = {11, 10, 8, 7, 6, 12, 13}; # DojoXXG # A",
"array which lists possible next steps for each current position and direction. Snake",
"left arrow v as a down arrow ^ as an up arrow \"\"\"",
"setup(): for i in range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d",
"(choices[1] == -1) : head = choices[0] # no second choice else: choice",
"code 13. >:0 <:7 ----- ^:5 | | v:1 v:12 | >:6 |",
"12 [5, 11] # 13 ] print moves \"\"\" A ----- F |",
"Snake head position and direction is coded like pictured below, i.e. when the",
"'tested i %d' %pins[i] display[tail % 7].write(1) #MRAA def loop(): global head global",
"-1], # 0 [13, 2], # 1 [3, -1], # 2 [4, -1],",
"] print moves \"\"\" A ----- F | | B | G |",
"9 [9, -1], # 10 [10, -1], # 11 [6, 11], # 12",
"\"\"\" WildSnakePy - WildSnakeUNO ported to Galileo (mraa native API) A two-segment snake",
"F | | B | G | ----- E | | C |",
"13, 7] display = [Gpio(i) for i in pins] print repr(display) head =",
"choice else: choice = random.choice([0,1]) print ' choice ' + str(choice) head =",
"second_choice moves = [ [1, -1], # 0 [13, 2], # 1 [3,",
"arrow \"\"\" # TODO: works, but needs cleanup from mraa import * import",
"in the same place is code 13. >:0 <:7 ----- ^:5 | |",
"pins = [8, 9, 10, 11, 12, 13, 7] display = [Gpio(i) for",
"range(SEGMENTS): display[i].dir(DIR_OUT) #MRAA print repr(display[i]) display[i].write(1) print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0)",
"= random.choice([0,1]) print ' choice ' + str(choice) head = choices[choice] print 'setup()'",
"[Gpio(i) for i in pins] print repr(display) head = 8 # segment B",
"choices = moves[head] if (choices[1] == -1) : head = choices[0] # no",
"| | ^:9 ----- <:3 >:10 To understand this diagram, read: > as",
"as an up arrow \"\"\" # TODO: works, but needs cleanup from mraa",
"4 [0, -1], # 5 [2, 8], # 6 [12, -1], # 7",
"B | G | ----- E | | C | D | -----",
"delay = pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA",
"= choices[0] # no second choice else: choice = random.choice([0,1]) print ' choice",
"print repr(display) head = 8 # segment B tail = 9 # segment",
"'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail % 7].write(0) #MRAA tail = head choices",
"{8, 9, 7, 12, 11, 10, 7, 13}; # A B C D",
"is encoded in the `moves` array which lists possible next steps for each",
"is 6, going left in the same place is code 13. >:0 <:7",
"is code 13. >:0 <:7 ----- ^:5 | | v:1 v:12 | >:6",
"[12, -1], # 7 [7, -1], # 8 [13, 8], # 9 [9,",
"snake slithers aimlessly over the display. On intersections, the next step is chosen",
"next steps for each current position and direction. Snake head position and direction",
"position and direction. Snake head position and direction is coded like pictured below,",
"| ----- \"\"\" # A B C D E F G #int display[]",
"down arrow ^ as an up arrow \"\"\" # TODO: works, but needs",
"and direction is coded like pictured below, i.e. when the snake head is",
"7 pins = [8, 9, 10, 11, 12, 13, 7] display = [Gpio(i)",
"7].write(1) #MRAA def loop(): global head global tail print ' head ' +",
"[0, -1], # 5 [2, 8], # 6 [12, -1], # 7 [7,",
"[6, 5], # 4 [0, -1], # 5 [2, 8], # 6 [12,",
"D E F G SEGMENTS = 7 pins = [8, 9, 10, 11,",
"print 'pin %d on' %pins[i] time.sleep(2) display[i].write(0) print 'tested i %d' %pins[i] display[tail",
"G #int display[] = {11, 10, 8, 7, 6, 12, 13}; # DojoXXG",
"% 7].write(1) #MRAA delay = pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0) display[tail",
"^:5 | | v:1 v:12 | >:6 | ^:8 ----- ^:4 | <:13|",
"from mraa import * import time, random # {first_choice, second_choice*} # * -1",
"* -1 means there is no second_choice moves = [ [1, -1], #",
"[8, 9, 10, 11, 12, 13, 7] display = [Gpio(i) for i in",
"no second choice else: choice = random.choice([0,1]) print ' choice ' + str(choice)",
"# 13 ] print moves \"\"\" A ----- F | | B |",
"{11, 10, 8, 7, 6, 12, 13}; # DojoXXG # A B G",
"arrow v as a down arrow ^ as an up arrow \"\"\" #",
"' + str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read() print 'delay %s'",
"WildSnakeUNO ported to Galileo (mraa native API) A two-segment snake slithers aimlessly over",
"v:12 | >:6 | ^:8 ----- ^:4 | <:13| v:2 v:11 | |",
"at the middle segment going right, the code is 6, going left in",
"| >:6 | ^:8 ----- ^:4 | <:13| v:2 v:11 | | ^:9",
"Most of the logic is encoded in the `moves` array which lists possible",
"chosen at random. Most of the logic is encoded in the `moves` array",
"display[head % 7].write(1) #MRAA delay = pot.read() print 'delay %s' % str(delay) time.sleep(delay/1000.0)",
"C D E F G #int display[] = {11, 10, 8, 7, 6,",
"+ str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read() print 'delay %s' %",
"----- E | | C | D | ----- \"\"\" # A B",
"| B | G | ----- E | | C | D |",
"# 9 [9, -1], # 10 [10, -1], # 11 [6, 11], #",
"| | C | D | ----- \"\"\" # A B C D",
"-1], # 7 [7, -1], # 8 [13, 8], # 9 [9, -1],",
"moves = [ [1, -1], # 0 [13, 2], # 1 [3, -1],",
"head is at the middle segment going right, the code is 6, going",
"% 7].write(1) #MRAA def loop(): global head global tail print ' head '",
"%pins[i] display[tail % 7].write(1) #MRAA def loop(): global head global tail print '",
"import * import time, random # {first_choice, second_choice*} # * -1 means there",
"possible next steps for each current position and direction. Snake head position and",
"[6, 11], # 12 [5, 11] # 13 ] print moves \"\"\" A",
"this diagram, read: > as a right arrow < as a left arrow",
"the display. On intersections, the next step is chosen at random. Most of",
"[4, -1], # 3 [6, 5], # 4 [0, -1], # 5 [2,",
"[13, 8], # 9 [9, -1], # 10 [10, -1], # 11 [6,",
"[13, 2], # 1 [3, -1], # 2 [4, -1], # 3 [6,",
"print ' tail ' + str(tail%7) display[head % 7].write(1) #MRAA delay = pot.read()",
"A ----- F | | B | G | ----- E | |",
"To understand this diagram, read: > as a right arrow < as a",
"# 6 [12, -1], # 7 [7, -1], # 8 [13, 8], #",
"8 # segment B tail = 9 # segment A pot = Aio(0)",
"E | | C | D | ----- \"\"\" # A B C",
"= [8, 9, 10, 11, 12, 13, 7] display = [Gpio(i) for i",
"when the snake head is at the middle segment going right, the code",
"11 [6, 11], # 12 [5, 11] # 13 ] print moves \"\"\"",
"= moves[head] if (choices[1] == -1) : head = choices[0] # no second",
"+ str(choice) head = choices[choice] print 'setup()' setup() print 'loop()' while True: loop()",
"A B C D E F G SEGMENTS = 7 pins = [8,",
"D | ----- \"\"\" # A B C D E F G #int"
] |
[
"2019/05/14 add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import",
"test for basic grid. content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest",
"(2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4)",
"import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph",
"= DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0),",
"(0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)]))",
"Unit Test On Grid description: This is the unit test for basic grid.",
"import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d",
"test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'):",
"Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add",
"4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))),",
"self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g",
"sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from",
"graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from",
"(1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2,",
"graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4,",
"self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0,",
"def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)])) if __name__ == '__main__':",
"On Grid description: This is the unit test for basic grid. content: -",
"description: This is the unit test for basic grid. content: - TestGrid -",
"(2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)]))",
"0), (1, 0), (0, 0), (2, 1), (0, 1), (2, 2), (1, 2),",
"def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0,",
"TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys import",
"'..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import",
"sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid,",
"3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)])) if __name__ ==",
"def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1,",
"self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3,",
"super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))),",
"for basic grid. content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update:",
"DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3),",
"test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)])) if __name__ == '__main__': unittest.main(verbosity=1)",
"super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4,",
"def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self,",
"self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0,",
"0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)])) if",
"self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0,",
"for DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest root = os.path.join(os.path.dirname(__file__), '..')",
"TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14 add TestGridDB -",
"class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self):",
"(2, 1), (0, 1), (2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def",
"# -*- coding: utf-8 -*- \"\"\" Unit Test On Grid description: This is",
"(3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def test_case2(self):",
"-*- coding: utf-8 -*- \"\"\" Unit Test On Grid description: This is the",
"(1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3,",
"graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'):",
"from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts",
"from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph",
"- TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14",
"self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4)",
"DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1),",
"set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase):",
"(1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4)",
"import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase):",
"set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g =",
"4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2, 1), (0,",
"graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class",
"2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1",
"TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14 add",
"(0, 1), (2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'):",
"self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)]))",
"self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0),",
"4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1,",
"__init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2",
"DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName)",
"class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0),",
"DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root)",
"latest update: - 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add test_case for",
"the unit test for basic grid. content: - TestGrid - TestGrid8D author: Shin-Fu",
"(3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3, 3)])) if __name__",
"GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import",
"1), (0, 1), (2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self,",
"-*- \"\"\" Unit Test On Grid description: This is the unit test for",
"author: Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15",
"This is the unit test for basic grid. content: - TestGrid - TestGrid8D",
"os import sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import",
"2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0,",
"add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys",
"1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class",
"import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4)",
"content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10 -",
"methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self):",
"(1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase):",
"1), (2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB,",
"0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self):",
"test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest root = os.path.join(os.path.dirname(__file__),",
"(2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName)",
"- 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\"",
"1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4,",
"2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import",
"root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid",
"(<NAME> latest update: - 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add test_case",
"4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3))",
"def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2,",
"2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)]))",
"def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3))",
"= DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0,",
"TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))),",
"2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest root",
"0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def",
"Test On Grid description: This is the unit test for basic grid. content:",
"self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1,",
"1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def",
"import sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights",
"test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0),",
"TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3,",
"3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def",
"unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import",
"self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1,",
"\"\"\" Unit Test On Grid description: This is the unit test for basic",
"DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3,",
"(2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D,",
"is the unit test for basic grid. content: - TestGrid - TestGrid8D author:",
"grid. content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10",
"def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3))",
"set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName)",
"(0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4)",
"from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self,",
"1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))),",
"TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3,",
"import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid,",
"(1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self,",
"\"\"\" import os import sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from",
"super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1),",
"= GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1,",
"4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0), (0, 3), (3,",
"1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'):",
"methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1,",
"self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0),",
"EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2, 1),",
"(1, 0), (0, 0), (2, 1), (0, 1), (2, 2), (1, 2), (0,",
"DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def",
"(1, 2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 =",
"methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4, 4) self.g1.set_search((0, 0), (3, 3)) self.g2 =",
"basic grid. content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME> latest update: -",
"test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2, 1), (0, 1), (2,",
"Grid description: This is the unit test for basic grid. content: - TestGrid",
"1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2,",
"import os import sys import unittest root = os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid",
"= DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0,",
"- TestGrid8D author: Shin-Fu (<NAME> latest update: - 2019/05/10 - 2019/05/14 add TestGridDB",
"0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName)",
"0), (2, 1), (0, 1), (2, 2), (1, 2), (0, 2)])) class TestGridDB(unittest.TestCase):",
"coding: utf-8 -*- \"\"\" Unit Test On Grid description: This is the unit",
"__init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1),",
"self.g1.set_search((0, 0), (3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def",
"def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2, 1), (0, 1),",
"self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(3, 0),",
"add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest root =",
"0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1,",
"set([(0, 1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1),",
"class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self):",
"unit test for basic grid. content: - TestGrid - TestGrid8D author: Shin-Fu (<NAME>",
"from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g =",
"2), (2, 3)])) class TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4,",
"self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph,",
"2), (0, 2)])) class TestGridDB(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGridDB, self).__init__(methodName) self.g1 = DynamicBoundGrid(4,",
"__init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0),",
"0), (0, 0), (2, 1), (0, 1), (2, 2), (1, 2), (0, 2)]))",
"EightDirectionGrid from graph.gridDB import DynamicBoundGrid, DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def",
"(0, 0), (2, 1), (0, 1), (2, 2), (1, 2), (0, 2)])) class",
"self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2, 1), (0, 1), (2, 2),",
"(0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 =",
"utf-8 -*- \"\"\" Unit Test On Grid description: This is the unit test",
"__init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0), (3, 3)) def",
"test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0),",
"GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0), (1, 2)]))",
"self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)]))",
"set([(2, 0), (1, 0), (0, 0), (2, 1), (0, 1), (2, 2), (1,",
"DynamicBoundGridWithShortcuts from graph.duality_graph import DualityGraph class TestGrid(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g",
"os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from graph.gridDB",
"1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0,",
"0), (1, 2)])) self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2),",
"0), (0, 1), (1, 1)])) class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1",
"- 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os import sys import unittest",
"= os.path.join(os.path.dirname(__file__), '..') sys.path.append(root) from graph.grid import GridWithWeights from graph.grid8d import EightDirectionGrid from",
"- 2019/05/14 add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts \"\"\" import os",
"= EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0), (0, 0), (2,",
"TestGrid8D(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))),",
"class TestDualityGraph(unittest.TestCase): def __init__(self, methodName='runTest'): super(TestDualityGraph, self).__init__(methodName) self.g1 = DualityGraph(4, 4) self.g1.set_search((0, 0),",
"def __init__(self, methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0,",
"super(TestGrid8D, self).__init__(methodName) self.g = EightDirectionGrid(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(2, 0), (1, 0),",
"update: - 2019/05/10 - 2019/05/14 add TestGridDB - 2019/05/15 add test_case for DynamicBoundGridWithShortcuts",
"0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class TestGrid8D(unittest.TestCase): def",
"methodName='runTest'): super(TestGrid, self).__init__(methodName) self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2,",
"3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1, 0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))),",
"set([(1, 0), (0, 1), (1, 1)])) def test_case2(self): self.assertSetEqual(set(self.g2.neighbors((0,0))), set([(1, 0), (0, 1),",
"self.g = GridWithWeights(4, 4) def test_case1(self): self.assertSetEqual(set(self.g.neighbors((1,1))), set([(0, 1), (2, 1), (1, 0),",
"3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))), set([(1,",
"self.assertSetEqual(set(self.g.neighbors((1,0))), set([(0, 0), (1, 1), (2, 0)])) self.assertSetEqual(set(self.g.neighbors((3,3))), set([(3, 2), (2, 3)])) class",
"(3, 3)) self.g2 = DynamicBoundGridWithShortcuts(4, 4) self.g2.set_search((0, 0), (3, 3)) def test_case1(self): self.assertSetEqual(set(self.g1.neighbors((0,0))),"
] |
[
"= '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python",
"Plugin to check HBase RegionServer requests imbalance via the HMaster UI Tested on",
"RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ =",
"self.is_ok(): self.msg += ' [min reqs/sec={} on {} / max reqs/sec={} on {}]'\\",
"LinkedIn # and optionally send me feedback to help steer this or other",
"lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple algo - let me",
"my code you're welcome to connect with me on LinkedIn # and optionally",
"| reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests) if __name__ == '__main__': CheckHBaseRegionServerBalance().main()",
"= int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to parse HBase Master",
"HBase 1.2 (Apache): ServerName | Start time | Version | Requests per Second",
"srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from",
"__author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x",
"len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance,",
"self.verbose or not self.is_ok(): self.msg += ' [min reqs/sec={} on {} / max",
"stats): lowest_requests = None highest_requests = None lowest_regionserver = None highest_regionserver = None",
"import os import sys import traceback try: from bs4 import BeautifulSoup except ImportError:",
"import unicode_literals #import logging #import json import os import sys import traceback try:",
"if self.verbose or not self.is_ok(): self.msg += ' [min reqs/sec={} on {} /",
"stats table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName | Start time",
"parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80)",
"stats table!') expected_header = 'Requests Per Second' col_index = len(th_list) - 2 found_header",
"time | Version | Requests per Second | Num. Regions # HBase 1.4",
"Tested on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0,",
"# super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port = 16010 self.path = '/master-status'",
"+0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying",
"raise UnknownError(\"non-integer found in Requests Per Second column for regionserver '{}'. {}\"\\ .format(regionserver,",
"[min reqs/sec={} on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver)",
"highest_requests = None lowest_regionserver = None highest_regionserver = None for regionserver in stats:",
"HBase RegionServer requests imbalance via the HMaster UI Tested on Apache HBase 0.95,",
"2.3: ServerName | Start time | Requests Per Second | Num. Regions #",
"1) * 100 num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance =",
"https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file # # If",
"found in Requests Per Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) #",
"stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple algo -",
"1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import from __future__ import division",
"for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this is to cast",
"= None highest_requests = None lowest_regionserver = None highest_regionserver = None for regionserver",
"import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__",
"= ['HBase Master', 'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth = False",
"'<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__()",
"22:46:34 +0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License: see",
"import isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError as _:",
"__future__ import division from __future__ import print_function from __future__ import unicode_literals #import logging",
"send me feedback to help steer this or other code I publish #",
"UnknownError(\"non-integer found in Requests Per Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg()))",
"table header found for column 4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header,",
"| Last Contact | Version | Requests Per Second | Num. Regions th_list",
"but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for row in",
"this is to cast string '1.0' to float and then cast to int",
"from __future__ import division from __future__ import print_function from __future__ import unicode_literals #import",
"HDP 2.3: ServerName | Start time | Requests Per Second | Num. Regions",
"in HDP 2.3: ServerName | Start time | Requests Per Second | Num.",
"= 16010 self.path = '/master-status' self.auth = False self.json = False self.msg =",
"Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # #",
"row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column in table not found! {}'.format(support_msg()))",
"Num. Regions # HBase 1.4 (Apache): ServerName | Start time | Last Contact",
"# https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file # #",
"not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second column for regionserver '{}'.",
"None for regionserver in stats: if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver",
"from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ =",
"in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in",
"sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural from",
"highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests)",
"1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import from",
"Num. Regions th_list = rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table header",
"len(th_list) < 4: raise UnknownError('no table header for base stats table!') expected_header =",
"= regionserver if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver = regionserver if",
"file # # If you're using my code you're welcome to connect with",
"2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name = ['HBase Master', 'HBase']",
"= soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2:",
"# \"\"\" Nagios Plugin to check HBase RegionServer requests imbalance via the HMaster",
"imbalance via the HMaster UI Tested on Apache HBase 0.95, 0.96, 0.98, 1.0,",
"masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows =",
"Python 3.x # super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port = 16010 self.path",
"# log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception #try: tab =",
"1.4 (Apache): ServerName | Start time | Last Contact | Version | Requests",
"optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\",",
"UnknownError(\"wrong table header found for column 4! Expected '{}' but got '{}'. {}\"\\",
"RegionServer requests imbalance via the HMaster UI Tested on Apache HBase 0.95, 0.96,",
"= '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance,",
"for this is to cast string '1.0' to float and then cast to",
"import print_function from __future__ import unicode_literals #import logging #import json import os import",
"table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec",
"break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per",
"HBase 1.4 (Apache): ServerName | Start time | Last Contact | Version |",
"or not self.is_ok(): self.msg += ' [min reqs/sec={} on {} / max reqs/sec={}",
"max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance",
"{'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2: raise UnknownError('no",
"int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to parse HBase Master UI",
"stats[regionserver] lowest_regionserver = regionserver if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver =",
"traceback try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir =",
"# # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase RegionServer requests imbalance",
"Start time | Version | Requests per Second | Num. Regions # HBase",
"reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second",
"# this masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table')",
"for regionserver in stats: if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver =",
"| Num. Regions # HBase 1.4 (Apache): ServerName | Start time | Last",
"end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): #",
"Second | Num. Regions th_list = rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no",
"| Start time | Requests Per Second | Num. Regions # HBase 1.2",
"float and then cast to int # ValueError: invalid literal for int() with",
"from harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError",
"not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec =",
"def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name",
"super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth",
"self).__init__() # Python 3.x # super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port =",
"Requests Per Second | Num. Regions # HBase 1.2 (Apache): ServerName | Start",
"lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple algo - let me know",
"support_msg())) stats = {} for row in rows[1:]: cols = row.findChildren('td') if len(cols)",
"regionserver rows found in base stats table! {}'.format(support_msg())) # HBase 1.1 in HDP",
"Regions # HBase 1.2 (Apache): ServerName | Start time | Version | Requests",
"import sys import traceback try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='')",
"| Num. Regions th_list = rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table",
"lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests is None:",
"self.msg += ' [min reqs/sec={} on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests,",
"2 found_header = th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table header found",
"cols = row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column in table not",
"0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import",
"be a better calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1) *",
"division from __future__ import print_function from __future__ import unicode_literals #import logging #import json",
"'='*80) # this masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table =",
"= os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils",
"highest_requests is None: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests:",
"= None highest_regionserver = None for regionserver in stats: if lowest_requests is None:",
"absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals",
"= regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver #",
"disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except",
"if len(th_list) < 4: raise UnknownError('no table header for base stats table!') expected_header",
"if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer",
"'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options()",
"lowest_requests = None highest_requests = None lowest_regionserver = None highest_regionserver = None for",
"HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from",
"# Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name = ['HBase",
"end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint:",
"'{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this is to cast string '1.0'",
"os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import",
"see accompanying Hari Sekhon LICENSE file # # If you're using my code",
"= (highest_requests - lowest_requests) / max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg",
"0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__",
"req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) #",
"{:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok():",
"column in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver:",
"cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise",
"sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position",
"int # ValueError: invalid literal for int() with base 10: '1.0' stats[regionserver] =",
"= 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance,",
"in stats: if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if",
"literal for int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError,",
"' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests) if __name__ == '__main__':",
"(Apache): ServerName | Start time | Last Contact | Version | Requests Per",
"# Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) #",
"highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver",
"raise UnknownError('failed to parse HBase Master UI status page. {}'.format(support_msg())) def process_stats(self, stats):",
"RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if",
"| Start time | Version | Requests per Second | Num. Regions #",
"exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if",
"None lowest_regionserver = None highest_regionserver = None for regionserver in stats: if lowest_requests",
"os import sys import traceback try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(),",
"is None: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests",
".format(expected_header, found_header, support_msg())) stats = {} for row in rows[1:]: cols = row.findChildren('td')",
"4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {}",
"support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='')",
"for base stats table!') expected_header = 'Requests Per Second' col_index = len(th_list) -",
"lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests,",
"# vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13",
"UnknownError('no regionserver rows found in base stats table! {}'.format(support_msg())) # HBase 1.1 in",
"| Version | Requests Per Second | Num. Regions th_list = rows[0].findChildren('th') if",
"int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): #",
"if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] >",
"def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser')",
"CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__()",
"= BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks",
"1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import from __future__ import division from",
"'0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x",
"super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup",
"1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import from __future__",
"100 num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}% across",
"'1.0' to float and then cast to int # ValueError: invalid literal for",
"parse HBase Master UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None",
"self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg += ' [min reqs/sec={} on {}",
"raise UnknownError(\"wrong table header found for column 4! Expected '{}' but got '{}'.",
"< lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple algo - let",
"2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License:",
"plural from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__",
".format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg += ' [min",
"pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin",
"soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this",
"to int # ValueError: invalid literal for int() with base 10: '1.0' stats[regionserver]",
"# Python 3.x # super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port = 16010",
"reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose",
"log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception #try: tab = soup.find('div',",
"tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if len(rows) <",
"len(th_list) - 2 found_header = th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table",
"rows[1:]: cols = row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column in table",
"{}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if",
".format(regionserver, support_msg())) # fix for this is to cast string '1.0' to float",
"'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth = False self.json = False",
"None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests is None: highest_requests =",
"# # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file #",
"add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req):",
"* 100 num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}%",
"= os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg,",
"try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__))",
"highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver",
"/ max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' |",
"import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir,",
"# Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins #",
"process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if",
"from __future__ import print_function from __future__ import unicode_literals #import logging #import json import",
"imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1) * 100 num_regionservers = len(stats)",
"table!') expected_header = 'Requests Per Second' col_index = len(th_list) - 2 found_header =",
"# fix for this is to cast string '1.0' to float and then",
"using my code you're welcome to connect with me on LinkedIn # and",
"time | Requests Per Second | Num. Regions # HBase 1.2 (Apache): ServerName",
"highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests) if",
"TypeError): # raise UnknownError('failed to parse HBase Master UI status page. {}'.format(support_msg())) def",
"Num. Regions # HBase 1.2 (Apache): ServerName | Start time | Version |",
"cast to int # ValueError: invalid literal for int() with base 10: '1.0'",
"bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir =",
"to parse HBase Master UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests =",
"HMaster UI Tested on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3,",
"False self.msg = 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def",
"None highest_requests = None lowest_regionserver = None highest_regionserver = None for regionserver in",
"self.path = '/master-status' self.auth = False self.json = False self.msg = 'HBase msg",
"= 'Requests Per Second' col_index = len(th_list) - 2 found_header = th_list[col_index].text if",
"base stats table!') expected_header = 'Requests Per Second' col_index = len(th_list) - 2",
"rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table header for base stats table!')",
"if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple algo",
"16010 self.path = '/master-status' self.auth = False self.json = False self.msg = 'HBase",
"regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not",
"= stats[regionserver] lowest_regionserver = regionserver if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver",
"!= expected_header: raise UnknownError(\"wrong table header found for column 4! Expected '{}' but",
"{}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName | Start time | Requests",
"column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this is to",
"reqs/sec={} on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg",
"if you think can be a better calculation imbalance = (highest_requests - lowest_requests)",
"think can be a better calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests,",
"stats = {} for row in rows[1:]: cols = row.findChildren('td') if len(cols) <",
"to cast string '1.0' to float and then cast to int # ValueError:",
"= cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second column",
"Contact | Version | Requests Per Second | Num. Regions th_list = rows[0].findChildren('th')",
"if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests is",
"isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second column for regionserver '{}'. {}\"\\",
"defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def",
"HBase 1.1 in HDP 2.3: ServerName | Start time | Requests Per Second",
"| Num. Regions # HBase 1.2 (Apache): ServerName | Start time | Version",
"# HBase 1.1 in HDP 2.3: ServerName | Start time | Requests Per",
"string '1.0' to float and then cast to int # ValueError: invalid literal",
"# License: see accompanying Hari Sekhon LICENSE file # # If you're using",
"on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1",
"4: raise UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if",
"accompanying Hari Sekhon LICENSE file # # If you're using my code you're",
"BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying",
"__version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() #",
"13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon",
"cast string '1.0' to float and then cast to int # ValueError: invalid",
"= len(th_list) - 2 found_header = th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong",
"Start time | Requests Per Second | Num. Regions # HBase 1.2 (Apache):",
"regionserver if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver]",
"Version | Requests per Second | Num. Regions # HBase 1.4 (Apache): ServerName",
"Start time | Last Contact | Version | Requests Per Second | Num.",
"| Requests Per Second | Num. Regions th_list = rows[0].findChildren('th') if len(th_list) <",
"page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests = None lowest_regionserver =",
"# HBase 1.4 (Apache): ServerName | Start time | Last Contact | Version",
"2.0, 2.1 \"\"\" from __future__ import absolute_import from __future__ import division from __future__",
"'HBase RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance)",
"ServerName | Start time | Version | Requests per Second | Num. Regions",
"lowest_requests) / max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg = 'HBase RegionServers",
"# ValueError: invalid literal for int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec))",
"time | Last Contact | Version | Requests Per Second | Num. Regions",
"Version | Requests Per Second | Num. Regions th_list = rows[0].findChildren('th') if len(th_list)",
"{}\"\\ .format(regionserver, support_msg())) # fix for this is to cast string '1.0' to",
"{}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance,",
"if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second column for regionserver",
"1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import from __future__ import",
"Per Second | Num. Regions th_list = rows[0].findChildren('th') if len(th_list) < 4: raise",
"Sekhon LICENSE file # # If you're using my code you're welcome to",
"ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try:",
"import traceback try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir",
"= '/master-status' self.auth = False self.json = False self.msg = 'HBase msg not",
"regionserver # simple algo - let me know if you think can be",
"'1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to parse",
"and optionally send me feedback to help steer this or other code I",
"self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content,",
"Requests Per Second | Num. Regions th_list = rows[0].findChildren('th') if len(th_list) < 4:",
"Master', 'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth = False self.json =",
"process_stats(self, stats): lowest_requests = None highest_requests = None lowest_regionserver = None highest_regionserver =",
"this or other code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin",
"Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name = ['HBase Master',",
"UnknownError('failed to parse HBase Master UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests",
"UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests = None",
"for int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError):",
"{} for row in rows[1:]: cols = row.findChildren('td') if len(cols) < 4: raise",
"# HBase 1.2 (Apache): ServerName | Start time | Version | Requests per",
"lowest_regionserver = regionserver if highest_requests is None: highest_requests = stats[regionserver] highest_regionserver = regionserver",
"(AttributeError, TypeError): # raise UnknownError('failed to parse HBase Master UI status page. {}'.format(support_msg()))",
"Second | Num. Regions # HBase 1.4 (Apache): ServerName | Start time |",
"Second' col_index = len(th_list) - 2 found_header = th_list[col_index].text if found_header != expected_header:",
"= cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec):",
"cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests Per Second column for",
"super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port",
"UnknownError('no table header for base stats table!') expected_header = 'Requests Per Second' col_index",
"column 4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats =",
"None highest_regionserver = None for regionserver in stats: if lowest_requests is None: lowest_requests",
"= th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table header found for column",
"stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver =",
"if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] <",
"2: raise UnknownError('no regionserver rows found in base stats table! {}'.format(support_msg())) # HBase",
"= None lowest_regionserver = None highest_regionserver = None for regionserver in stats: if",
"harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>'",
"class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x #",
"len(rows) < 2: raise UnknownError('no regionserver rows found in base stats table! {}'.format(support_msg()))",
"License: see accompanying Hari Sekhon LICENSE file # # If you're using my",
"regionserver in stats: if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver",
"msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True,",
"{} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg +=",
"HBase Master UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests",
"steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios",
"print_function from __future__ import unicode_literals #import logging #import json import os import sys",
"highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver]",
"to help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon #",
"calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1) * 100 num_regionservers =",
"raise UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:'",
"= regionserver # simple algo - let me know if you think can",
"I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase RegionServer",
"__future__ import unicode_literals #import logging #import json import os import sys import traceback",
"found_header = th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table header found for",
"= stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver",
"you're using my code you're welcome to connect with me on LinkedIn #",
"| Version | Requests per Second | Num. Regions # HBase 1.4 (Apache):",
"lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests is None: highest_requests = stats[regionserver]",
"= False self.msg = 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50)",
"simple algo - let me know if you think can be a better",
"lowest_regionserver = regionserver # simple algo - let me know if you think",
"sys import traceback try: from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4)",
"4: raise UnknownError('no table header for base stats table!') expected_header = 'Requests Per",
"1.1 in HDP 2.3: ServerName | Start time | Requests Per Second |",
"expected_header: raise UnknownError(\"wrong table header found for column 4! Expected '{}' but got",
"# simple algo - let me know if you think can be a",
"'/master-status' self.auth = False self.json = False self.msg = 'HBase msg not defined'",
"num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg += ' [min reqs/sec={}",
"{}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for row in rows[1:]: cols =",
"BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib')",
"self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): #",
"unicode_literals #import logging #import json import os import sys import traceback try: from",
"| Start time | Last Contact | Version | Requests Per Second |",
"stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to parse HBase",
"RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg += '",
"= rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table header for base stats",
"#!/usr/bin/env python # vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2018-07-13 22:46:34 +0100",
"sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self): # Python",
"Requests Per Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for",
"= tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver rows",
"ValueError: invalid literal for int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats)",
"Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\"",
"self.msg = 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self):",
"base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed",
"stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests:",
"json import os import sys import traceback try: from bs4 import BeautifulSoup except",
"__future__ import print_function from __future__ import unicode_literals #import logging #import json import os",
"> highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests",
"know if you think can be a better calculation imbalance = (highest_requests -",
"support_msg())) # fix for this is to cast string '1.0' to float and",
"UI Tested on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2, 1.3, 1.4,",
"'{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for row",
"| Requests Per Second | Num. Regions # HBase 1.2 (Apache): ServerName |",
"'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception",
"as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin):",
"header found for column 4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header,",
"'{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for row in rows[1:]: cols",
"raise UnknownError('no table header for base stats table!') expected_header = 'Requests Per Second'",
"+= ' [min reqs/sec={} on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver,",
"on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\",
"(Apache): ServerName | Start time | Version | Requests per Second | Num.",
"2.1 \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import",
".format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(),",
"prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'})",
"requests imbalance via the HMaster UI Tested on Apache HBase 0.95, 0.96, 0.98,",
"for column 4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats",
"found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip()",
"rows = table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver rows found in",
"Regions # HBase 1.4 (Apache): ServerName | Start time | Last Contact |",
"< 4: raise UnknownError('no table header for base stats table!') expected_header = 'Requests",
"code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase",
"soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2: raise",
"Per Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this",
"= 'HBase RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers))",
"self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup =",
"in base stats table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName |",
"Requests per Second | Num. Regions # HBase 1.4 (Apache): ServerName | Start",
"Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for",
"on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg +=",
"# https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase RegionServer requests imbalance via",
"__init__(self): # Python 2.x super(CheckHBaseRegionServerBalance, self).__init__() # Python 3.x # super().__init__() self.name =",
"print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: #",
"{} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += '",
"isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(),",
"= {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not",
"ServerName | Start time | Requests Per Second | Num. Regions # HBase",
"let me know if you think can be a better calculation imbalance =",
"Nagios Plugin to check HBase RegionServer requests imbalance via the HMaster UI Tested",
"th_list = rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table header for base",
"UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in",
"10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to",
"in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0] if 'Total:' in regionserver: break",
"ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class",
"os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError,",
"python # vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri,",
"/ max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec",
"from __future__ import unicode_literals #import logging #import json import os import sys import",
"except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0'",
"'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural",
"UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4)",
"super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG):",
"imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or",
"Second | Num. Regions # HBase 1.2 (Apache): ServerName | Start time |",
"'Total:' in regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found",
"2018) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file",
"Regions th_list = rows[0].findChildren('th') if len(th_list) < 4: raise UnknownError('no table header for",
"<NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins",
"row in rows[1:]: cols = row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column",
"not self.is_ok(): self.msg += ' [min reqs/sec={} on {} / max reqs/sec={} on",
"vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul",
"me feedback to help steer this or other code I publish # #",
"harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon import RestNagiosPlugin except ImportError as",
"raise UnknownError('no regionserver rows found in base stats table! {}'.format(support_msg())) # HBase 1.1",
"Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE",
"publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase RegionServer requests",
"- let me know if you think can be a better calculation imbalance",
"status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests = None lowest_regionserver",
"# # Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018)",
"# and optionally send me feedback to help steer this or other code",
"max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{}",
"welcome to connect with me on LinkedIn # and optionally send me feedback",
"then cast to int # ValueError: invalid literal for int() with base 10:",
"= {} for row in rows[1:]: cols = row.findChildren('td') if len(cols) < 4:",
"try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon",
"is to cast string '1.0' to float and then cast to int #",
"logging #import json import os import sys import traceback try: from bs4 import",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function from",
"print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def __init__(self):",
"this masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows",
"stats[regionserver] lowest_regionserver = regionserver # simple algo - let me know if you",
"expected_header = 'Requests Per Second' col_index = len(th_list) - 2 found_header = th_list[col_index].text",
"for row in rows[1:]: cols = row.findChildren('td') if len(cols) < 4: raise UnknownError('4th",
"in Requests Per Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix",
"__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__",
"found_header != expected_header: raise UnknownError(\"wrong table header found for column 4! Expected '{}'",
"# raise UnknownError('failed to parse HBase Master UI status page. {}'.format(support_msg())) def process_stats(self,",
"# # If you're using my code you're welcome to connect with me",
"#import json import os import sys import traceback try: from bs4 import BeautifulSoup",
"if len(cols) < 4: raise UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver",
"libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position from harisekhon.utils import isInt,",
"= False self.json = False self.msg = 'HBase msg not defined' def add_options(self):",
"plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg += ' [min reqs/sec={} on",
"check HBase RegionServer requests imbalance via the HMaster UI Tested on Apache HBase",
"(Fri, 13 Jul 2018) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari",
"self.validate_thresholds(percent=True, optional=True) def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup",
"if found_header != expected_header: raise UnknownError(\"wrong table header found for column 4! Expected",
"= stats[regionserver] lowest_regionserver = regionserver # simple algo - let me know if",
"table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver rows found in base stats",
"fix for this is to cast string '1.0' to float and then cast",
"None: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests =",
"= row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column in table not found!",
"#except (AttributeError, TypeError): # raise UnknownError('failed to parse HBase Master UI status page.",
"lowest_regionserver = None highest_regionserver = None for regionserver in stats: if lowest_requests is",
"better calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1) * 100 num_regionservers",
"Last Contact | Version | Requests Per Second | Num. Regions th_list =",
"self.auth = False self.json = False self.msg = 'HBase msg not defined' def",
"self.json = False self.msg = 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options()",
"if len(rows) < 2: raise UnknownError('no regionserver rows found in base stats table!",
"table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName | Start time |",
"+= ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests) if __name__ ==",
"feedback to help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon",
"except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir)",
"3.x # super().__init__() self.name = ['HBase Master', 'HBase'] self.default_port = 16010 self.path =",
"_: print(traceback.format_exc(), end='') sys.exit(4) __author__ = '<NAME>' __version__ = '0.3.0' class CheckHBaseRegionServerBalance(RestNagiosPlugin): def",
"ServerName | Start time | Last Contact | Version | Requests Per Second",
"#import logging #import json import os import sys import traceback try: from bs4",
"you think can be a better calculation imbalance = (highest_requests - lowest_requests) /",
"= stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver",
"' [min reqs/sec={} on {} / max reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests,",
"< 2: raise UnknownError('no regionserver rows found in base stats table! {}'.format(support_msg())) #",
"# If you're using my code you're welcome to connect with me on",
"num_regionservers = len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}% across {}",
"code you're welcome to connect with me on LinkedIn # and optionally send",
"= regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if",
"= table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver rows found in base",
"= len(stats) self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\",
"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"import division from __future__ import print_function from __future__ import unicode_literals #import logging #import",
"found for column 4! Expected '{}' but got '{}'. {}\"\\ .format(expected_header, found_header, support_msg()))",
"got '{}'. {}\"\\ .format(expected_header, found_header, support_msg())) stats = {} for row in rows[1:]:",
"on LinkedIn # and optionally send me feedback to help steer this or",
"col_index = len(th_list) - 2 found_header = th_list[col_index].text if found_header != expected_header: raise",
"base stats table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName | Start",
"found in base stats table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3: ServerName",
"tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver rows found",
"Master UI status page. {}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests =",
"the HMaster UI Tested on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1, 1.2,",
"can be a better calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1)",
"| Requests per Second | Num. Regions # HBase 1.4 (Apache): ServerName |",
"table header for base stats table!') expected_header = 'Requests Per Second' col_index =",
"Author: <NAME> # Date: 2018-07-13 22:46:34 +0100 (Fri, 13 Jul 2018) # #",
"soup.prettify(), '='*80) # this masks underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table",
"Per Second' col_index = len(th_list) - 2 found_header = th_list[col_index].text if found_header !=",
"regionserver: break reqs_per_sec = cols[col_index].text.strip() if not isInt(reqs_per_sec): raise UnknownError(\"non-integer found in Requests",
"< 4: raise UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver = cols[0].text.strip().split(',')[0]",
"highest_regionserver = None for regionserver in stats: if lowest_requests is None: lowest_requests =",
"or other code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to",
"a better calculation imbalance = (highest_requests - lowest_requests) / max(highest_requests, 1) * 100",
"{}'.format(support_msg())) def process_stats(self, stats): lowest_requests = None highest_requests = None lowest_regionserver = None",
"is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests is None: highest_requests",
"#try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr') if len(rows)",
"not defined' def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True)",
"rows found in base stats table! {}'.format(support_msg())) # HBase 1.1 in HDP 2.3:",
"- lowest_requests) / max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg = 'HBase",
"table = tab.find_next('table') rows = table.findChildren('tr') if len(rows) < 2: raise UnknownError('no regionserver",
"per Second | Num. Regions # HBase 1.4 (Apache): ServerName | Start time",
"highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver]",
"'Requests Per Second' col_index = len(th_list) - 2 found_header = th_list[col_index].text if found_header",
"self.process_stats(stats) #except (AttributeError, TypeError): # raise UnknownError('failed to parse HBase Master UI status",
"with me on LinkedIn # and optionally send me feedback to help steer",
"log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception #try: tab",
"help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\"",
"Second column for regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this is",
"# # License: see accompanying Hari Sekhon LICENSE file # # If you're",
"1.2 (Apache): ServerName | Start time | Version | Requests per Second |",
"len(cols) < 4: raise UnknownError('4th column in table not found! {}'.format(support_msg())) regionserver =",
"to connect with me on LinkedIn # and optionally send me feedback to",
"Per Second | Num. Regions # HBase 1.2 (Apache): ServerName | Start time",
"#if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(), '='*80) # this masks underlying exception #try:",
"across {} RegionServer{}'\\ .format(imbalance, num_regionservers, plural(num_regionservers)) self.check_thresholds(imbalance) if self.verbose or not self.is_ok(): self.msg",
"optionally send me feedback to help steer this or other code I publish",
"0.98, 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1 \"\"\" from __future__ import absolute_import",
"Hari Sekhon LICENSE file # # If you're using my code you're welcome",
"stats: if lowest_requests is None: lowest_requests = stats[regionserver] lowest_regionserver = regionserver if highest_requests",
"regionserver if stats[regionserver] < lowest_requests: lowest_requests = stats[regionserver] lowest_regionserver = regionserver # simple",
"me know if you think can be a better calculation imbalance = (highest_requests",
"highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver] < lowest_requests: lowest_requests =",
"th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table header found for column 4!",
"https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check HBase RegionServer requests imbalance via the",
"header for base stats table!') expected_header = 'Requests Per Second' col_index = len(th_list)",
"stats[regionserver] highest_regionserver = regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver =",
"from bs4 import BeautifulSoup except ImportError: print(traceback.format_exc(), end='') sys.exit(4) srcdir = os.path.abspath(os.path.dirname(__file__)) libdir",
"other code I publish # # https://www.linkedin.com/in/harisekhon # \"\"\" Nagios Plugin to check",
"['HBase Master', 'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth = False self.json",
"self.name = ['HBase Master', 'HBase'] self.default_port = 16010 self.path = '/master-status' self.auth =",
"underlying exception #try: tab = soup.find('div', {'id':'tab_baseStats'}) table = tab.find_next('table') rows = table.findChildren('tr')",
"and then cast to int # ValueError: invalid literal for int() with base",
"def process_stats(self, stats): lowest_requests = None highest_requests = None lowest_regionserver = None highest_regionserver",
"self.msg = 'HBase RegionServers reqs/sec imbalance = {:.0f}% across {} RegionServer{}'\\ .format(imbalance, num_regionservers,",
"def add_options(self): super(CheckHBaseRegionServerBalance, self).add_options() self.add_thresholds(default_warning=50) def process_options(self): super(CheckHBaseRegionServerBalance, self).process_options() self.validate_thresholds(percent=True, optional=True) def parse(self,",
"self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={} highest_requests_per_sec={}'\\ .format(imbalance, self.get_perf_thresholds(), lowest_requests, highest_requests) if __name__",
"you're welcome to connect with me on LinkedIn # and optionally send me",
"in rows[1:]: cols = row.findChildren('td') if len(cols) < 4: raise UnknownError('4th column in",
"to float and then cast to int # ValueError: invalid literal for int()",
"self.default_port = 16010 self.path = '/master-status' self.auth = False self.json = False self.msg",
"- 2 found_header = th_list[col_index].text if found_header != expected_header: raise UnknownError(\"wrong table header",
"= None for regionserver in stats: if lowest_requests is None: lowest_requests = stats[regionserver]",
"regionserver if stats[regionserver] > highest_requests: highest_requests = stats[regionserver] highest_regionserver = regionserver if stats[regionserver]",
"# pylint: disable=wrong-import-position from harisekhon.utils import isInt, support_msg, UnknownError, plural from harisekhon import",
"algo - let me know if you think can be a better calculation",
"with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except (AttributeError, TypeError): # raise",
"False self.json = False self.msg = 'HBase msg not defined' def add_options(self): super(CheckHBaseRegionServerBalance,",
"found_header, support_msg())) stats = {} for row in rows[1:]: cols = row.findChildren('td') if",
"regionserver '{}'. {}\"\\ .format(regionserver, support_msg())) # fix for this is to cast string",
"If you're using my code you're welcome to connect with me on LinkedIn",
"def parse(self, req): soup = BeautifulSoup(req.content, 'html.parser') #if log.isEnabledFor(logging.DEBUG): # log.debug(\"BeautifulSoup prettified:\\n%s\\n%s\", soup.prettify(),",
"via the HMaster UI Tested on Apache HBase 0.95, 0.96, 0.98, 1.0, 1.1,",
"import absolute_import from __future__ import division from __future__ import print_function from __future__ import",
"(highest_requests - lowest_requests) / max(highest_requests, 1) * 100 num_regionservers = len(stats) self.msg =",
"reqs/sec={} on {}]'\\ .format(lowest_requests, lowest_regionserver, highest_requests, highest_regionserver) self.msg += ' | reqs_per_sec_balance={:.2f}%{} lowest_requests_per_sec={}",
"LICENSE file # # If you're using my code you're welcome to connect",
"connect with me on LinkedIn # and optionally send me feedback to help",
"\"\"\" Nagios Plugin to check HBase RegionServer requests imbalance via the HMaster UI",
"to check HBase RegionServer requests imbalance via the HMaster UI Tested on Apache",
"me on LinkedIn # and optionally send me feedback to help steer this",
"invalid literal for int() with base 10: '1.0' stats[regionserver] = int(float(reqs_per_sec)) self.process_stats(stats) #except"
] |
[
"api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url =",
"\"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main():",
"} response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\")",
"\"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\":",
"response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload",
"{ \"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response)",
"server_response def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\":",
"\"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link",
"server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num,",
"fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num =",
"extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url)",
"int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response",
"extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"]",
"= f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link",
"print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\") if __name__ == \"__main__\":",
"def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url",
"urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response =",
"requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload",
"5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv()",
"with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num =",
"= \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token,",
"%s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\") if __name__ == \"__main__\": main()",
"comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename",
"import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension def",
"= { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url, params=payload)",
"import requests from dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension =",
"-212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response",
"= vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as",
"= requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo,",
"def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\":",
"requests.HTTPError as err: print(err) except requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\",",
"from dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return",
"= converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files",
"in api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url",
"uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id,",
"check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link",
"converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\"",
"requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server,",
"link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\"",
"vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response =",
"media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError as err: print(\"Connection Error. Check",
"212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response = requests.post(",
"converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return",
"converted_response = response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name",
"token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def",
"check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload =",
"def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content)",
"f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link =",
"hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return",
"= int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status()",
"response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link)",
"server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\":",
"= server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id",
"f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if \"error\" in api_response: raise",
"file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response",
"= get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments",
"API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token,",
"first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\"",
"\"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response = requests.post( url,",
"try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img",
"= server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img,",
"\"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" }",
"response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"]",
"token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response",
"check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] )",
"response = requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"]",
"vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError as err:",
"requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response = requests.get(url)",
"= \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url,",
"response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url):",
"publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError as",
"import splitext from urllib.parse import urlparse import requests from dotenv import load_dotenv def",
"filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic():",
"response = requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def",
"print(err) except requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError",
"def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963,",
"\"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json())",
"return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num =",
"publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\":",
"os.path import splitext from urllib.parse import urlparse import requests from dotenv import load_dotenv",
"= response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\"",
"last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json() comments =",
"= upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic(",
"except requests.HTTPError as err: print(err) except requests.ConnectionError as err: print(\"Connection Error. Check Internet",
"= \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response",
"= requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension",
"response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token,",
"comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link,",
"as err: print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\") if __name__",
"server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files = { \"photo\":",
"file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num)",
"urllib.parse import urlparse import requests from dotenv import load_dotenv def get_file_extension(link): link_path =",
"server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group(",
"raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\"",
"\"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token):",
"} response = requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response",
"= response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename,",
"server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id =",
"def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"]",
"= { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\":",
"5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link =",
"requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments",
"= response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name =",
"payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server,",
"except OSError as err: print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\")",
"load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response",
"import os import random from os.path import splitext from urllib.parse import urlparse import",
"VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\":",
"os import random from os.path import splitext from urllib.parse import urlparse import requests",
"server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except",
"file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num,",
"response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num",
"os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link)",
"= response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename,",
"comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response =",
"{ \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status()",
"filename, comments def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK",
"= server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id",
"files = { \"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response =",
"last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file:",
"server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file:",
"Error. Check Internet connection.\\n\", str(err)) except OSError as err: print(\"Error: %s - %s.\"",
"def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files = { \"photo\": file,",
"open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num())",
"server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id =",
"download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def",
"token, \"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response =",
"\"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload =",
"1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url,",
"random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json() comments",
"return last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as",
"group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError",
"comments, group_owner_id, media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError as err: print(\"Connection",
"= requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num =",
"\"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, }",
"} response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def",
"owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\":",
"converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with",
"main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token)",
"file: files = { \"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response",
"from urllib.parse import urlparse import requests from dotenv import load_dotenv def get_file_extension(link): link_path",
"vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id): url =",
"download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError(",
"= upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response",
"{ \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter,",
"except requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError as",
"= \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo,",
"media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err: print(err)",
"dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension",
"def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token,",
"err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError as err: print(\"Error: %s",
"with open(filename, \"rb\") as file: files = { \"photo\": file, } response =",
"upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token,",
"= requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token,",
"hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131,",
"= { \"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json()",
"\"hash\": hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response)",
"params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id):",
"server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter): url =",
"= requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link",
"\"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload)",
"comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status()",
"\"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response",
"} response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"]",
"= f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if \"error\" in api_response:",
"vk_response def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\":",
"if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK API\", api_response[\"error\"][\"error_msg\"] ) def",
"url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\":",
"requests.post( url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments,",
"def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link =",
"group_owner_id, media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError as err: print(\"Connection Error.",
"def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url",
"\"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return",
"\"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\":",
"splitext from urllib.parse import urlparse import requests from dotenv import load_dotenv def get_file_extension(link):",
"params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename,",
"files=files) response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter):",
"server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"]",
"random from os.path import splitext from urllib.parse import urlparse import requests from dotenv",
"as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num =",
"\"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response =",
"= get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash",
"= random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json()",
") def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963,",
"url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, }",
"err: print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\") if __name__ ==",
"comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response):",
"vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err: print(err) except requests.ConnectionError",
"as err: print(err) except requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\", str(err))",
"212094963, \"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response)",
"Check Internet connection.\\n\", str(err)) except OSError as err: print(\"Error: %s - %s.\" %",
"response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, \"wb\")",
"requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension =",
"check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload =",
"= requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response =",
"get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash =",
"response.raise_for_status() server_response = response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter): url",
"get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131,",
"\"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json()",
"get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url =",
"filename) return filename, comments def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка",
"\"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\" } response =",
"as err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError as err: print(\"Error:",
"OSError as err: print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally: os.remove(f\"./{filename}\") if",
"urlparse import requests from dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension",
"response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try:",
"response.json() check_api_response(server_response) return server_response def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload",
"comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"]",
"fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url =",
"converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files =",
"upload_url): with open(filename, \"rb\") as file: files = { \"photo\": file, } response",
"err: print(err) except requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except",
"f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token =",
"params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments =",
"server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash)",
"open(filename, \"rb\") as file: files = { \"photo\": file, } response = requests.post(upload_url,",
"extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename,",
"\"attachments\": f\"photo{owner_id}_{media_id}\" } response = requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token",
"vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err:",
"import urlparse import requests from dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path",
"last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status() with",
"import random from os.path import splitext from urllib.parse import urlparse import requests from",
"api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = { \"access_token\": token, \"group_id\":",
"upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files = { \"photo\": file, }",
"response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response",
"photo, \"server\": server, \"hash\": hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status() vk_response",
"= { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\":",
"= os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename,",
"comments def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с VK API\",",
"\"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status()",
"= fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num",
"url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def",
"media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments,",
"return vk_response def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = {",
"1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response =",
"comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1,",
"\"rb\") as file: files = { \"photo\": file, } response = requests.post(upload_url, files=files)",
"server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id)",
"= converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if",
"response = requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return",
"upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\":",
"= requests.post(url, params=payload) response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename,",
"filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if \"error\" in",
"vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments,",
"url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url) response.raise_for_status() converted_response = response.json() comments = converted_response[\"alt\"]",
"requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1",
"url, params=payload) response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id,",
"last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response = requests.get(url)",
"response.raise_for_status() check_api_response(response.json()) def main(): load_dotenv() vk_token = os.getenv(\"VK_ACCESS_TOKEN\") try: filename, comments = fetch_random_comic()",
"= urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response",
"load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1] return extension def get_last_comic_num():",
"\"server\": server, \"hash\": hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status() vk_response =",
"as file: files = { \"photo\": file, } response = requests.post(upload_url, files=files) response.raise_for_status()",
"payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131,",
"requests.ConnectionError as err: print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError as err:",
"str(err)) except OSError as err: print(\"Error: %s - %s.\" % (err.filename, err.strerror)) finally:",
"с VK API\", api_response[\"error\"][\"error_msg\"] ) def get_server_link(token): url = \"https://api.vk.com/method/photos.getWallUploadServer\" payload = {",
"def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return",
"get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def",
"payload = { \"access_token\": token, \"group_id\": 212094963, \"v\": 5.131, } response = requests.get(url,",
"= response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id): url = \"https://api.vk.com/method/wall.post\"",
"return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as file: files = {",
"url = \"https://api.vk.com/method/wall.post\" payload = { \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\":",
"= 1 last_comic_num = int(get_last_comic_num()) comic_num = random.randint(first_comic_num, last_comic_num) url = f\"https://xkcd.com/{comic_num}/info.0.json\" response",
"print(\"Connection Error. Check Internet connection.\\n\", str(err)) except OSError as err: print(\"Error: %s -",
"connection.\\n\", str(err)) except OSError as err: print(\"Error: %s - %s.\" % (err.filename, err.strerror))",
"uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token,",
"check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\") as",
"response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def upload_img_to_server(filename, upload_url): with open(filename, \"rb\")",
"from os.path import splitext from urllib.parse import urlparse import requests from dotenv import",
"server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"]",
"\"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num = 1 last_comic_num = int(get_last_comic_num()) comic_num",
"5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response = requests.post( url, params=payload)",
"= vk_response[\"response\"][0][\"id\"] publish_comic( vk_token, comments, group_owner_id, media_id) except requests.HTTPError as err: print(err) except",
"response.raise_for_status() vk_response = response.json() check_api_response(vk_response) return vk_response def publish_comic(token, comments, owner_id, media_id): url",
"upload_img_to_server(filename, server_link) uploaded_img = server_response[\"photo\"] server_num = server_response[\"server\"] server_hash = server_response[\"hash\"] vk_response =",
"Internet connection.\\n\", str(err)) except OSError as err: print(\"Error: %s - %s.\" % (err.filename,",
"converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename) return filename, comments def check_api_response(api_response): if \"error\"",
"return filename, comments def check_api_response(api_response): if \"error\" in api_response: raise requests.HTTPError( \"Ошибка с",
"server_hash = server_response[\"hash\"] vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"]",
"return server_response def upload_img_to_group(token, photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = {",
"= converted_response[\"alt\"] comic_link = converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename =",
"photo, server, hash_parameter): url = \"https://api.vk.com/method/photos.saveWallPhoto\" payload = { \"access_token\": token, \"group_id\": 212094963,",
"\"group_id\": 212094963, \"v\": 5.131, \"photo\": photo, \"server\": server, \"hash\": hash_parameter, } response =",
"get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num",
"response = requests.get(url) response.raise_for_status() with open(filename, \"wb\") as file: file.write(response.content) def fetch_random_comic(): first_comic_num",
"{ \"owner_id\": -212094963, \"from_group\": 1, \"message\": comments, \"access_token\": token, \"v\": 5.131, \"attachments\": f\"photo{owner_id}_{media_id}\"",
"= converted_response[\"img\"] extension = get_file_extension(comic_link) comic_name = converted_response[\"safe_title\"] filename = f\"{comic_name}{extension}\" download_comic(comic_link, filename)",
"requests from dotenv import load_dotenv def get_file_extension(link): link_path = urlparse(link).path extension = splitext(link_path)[-1]",
"= splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status()",
"splitext(link_path)[-1] return extension def get_last_comic_num(): url = \"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num",
"requests.get(url, params=payload) response.raise_for_status() converted_response = response.json() check_api_response(converted_response) server_link = converted_response[\"response\"][\"upload_url\"] return server_link def",
"server, \"hash\": hash_parameter, } response = requests.post( url, params=payload) response.raise_for_status() vk_response = response.json()",
"response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename): response = requests.get(url) response.raise_for_status()",
"vk_response = upload_img_to_group( vk_token, uploaded_img, server_num, server_hash) group_owner_id = vk_response[\"response\"][0][\"owner_id\"] media_id = vk_response[\"response\"][0][\"id\"]",
"\"https://xkcd.com/info.0.json\" response = requests.get(url) response.raise_for_status() last_comic_num = response.json()[\"num\"] return last_comic_num def download_comic(url, filename):",
"filename, comments = fetch_random_comic() server_link = get_server_link(vk_token) server_response = upload_img_to_server(filename, server_link) uploaded_img ="
] |
[
"django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter =",
"from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',) prepopulated_fields = {'slug':",
"your models here. from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta)",
"# Register your models here. from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import",
"fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',) prepopulated_fields = {'slug': ('descricao',",
"import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',) prepopulated_fields = {'slug': ('descricao', )}",
"register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',) prepopulated_fields",
"here. from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin):",
"Register your models here. from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta",
"from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter",
"ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',) prepopulated_fields =",
"import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class ConsultaAdmin(ModelAdmin): list_filter = ('paciente',)",
"models here. from django.contrib.admin import register, ModelAdmin from fitbox.consultas.models import Consulta @register(Consulta) class"
] |
[
"= '<NAME>' __email__ = '<EMAIL>' __version__ = '0.1.0' from .naughty_string_validator import NaughtyStringValidator, SRC_DIRECTORY",
"__author__ = '<NAME>' __email__ = '<EMAIL>' __version__ = '0.1.0' from .naughty_string_validator import NaughtyStringValidator,"
] |
[
"GameConstant for available type) -> game configuration for game type, could be bot",
"or 1 (only needed for player vs bot) thinking_time: float -> Maximal time",
"bot or bot vs bot) is_dump: bool -> is model loaded from bin",
"2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type = game_type self.player_choice = player_choice",
"type) -> game configuration for game type, could be bot vs bot, player",
"and player vs player player_choice: int -> Could be 0 or 1 (only",
"ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, { ShapeConstant.CROSS:",
"if self.player_choice == None: self.player_choice = -1 self.thinking_time = thinking_time def __str__(self): ret",
"[ATTRIBUTES] row: int -> boards configuration row shape col: int -> boards configuration",
"file \"\"\" def __init__( self, row: int, col: int, game_type: int, player_choice: int,",
"(n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type = game_type self.player_choice",
"boards configuration row shape col: int -> boards configuration column shape game_type: int",
"(only needed for player vs bot or bot vs bot) is_dump: bool ->",
"be bot vs bot, player vs bot, and player vs player player_choice: int",
"for player vs bot) thinking_time: float -> Maximal time for bot to think",
"ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, { ShapeConstant.CROSS: n_quota - (n_quota //",
"{ ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, }, ]",
"{self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n'",
"player vs bot) thinking_time: float -> Maximal time for bot to think (only",
"self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret",
"// 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, { ShapeConstant.CROSS: n_quota -",
"= '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump:",
"}, { ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, },",
"0 or 1 (only needed for player vs bot) thinking_time: float -> Maximal",
"game configuration for game type, could be bot vs bot, player vs bot,",
"bot to think (only needed for player vs bot or bot vs bot)",
"int (Look at GameConstant for available type) -> game configuration for game type,",
"bot) thinking_time: float -> Maximal time for bot to think (only needed for",
"= player_choice # 0 or 1 if self.player_choice == None: self.player_choice = -1",
"\"\"\" Class representation for configuration needed in game [ATTRIBUTES] row: int -> boards",
"+= f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret +=",
"bot vs bot) is_dump: bool -> is model loaded from bin file \"\"\"",
"vs bot) thinking_time: float -> Maximal time for bot to think (only needed",
"f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type:",
"from src.constant import ShapeConstant class Config: \"\"\" Class representation for configuration needed in",
"row: int -> boards configuration row shape col: int -> boards configuration column",
"is_dump: bool -> is model loaded from bin file \"\"\" def __init__( self,",
"float, ): self.row = row self.col = col self.is_dump = is_dump n_quota =",
"1 if self.player_choice == None: self.player_choice = -1 self.thinking_time = thinking_time def __str__(self):",
"__init__( self, row: int, col: int, game_type: int, player_choice: int, is_dump: bool, thinking_time:",
"ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret += f'thinking_time: {self.thinking_time}\\n' return",
"self.game_type = game_type self.player_choice = player_choice # 0 or 1 if self.player_choice ==",
"-> boards configuration row shape col: int -> boards configuration column shape game_type:",
"(n_quota // 2), }, { ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota",
"for bot to think (only needed for player vs bot or bot vs",
"\"\"\" def __init__( self, row: int, col: int, game_type: int, player_choice: int, is_dump:",
"thinking_time: float, ): self.row = row self.col = col self.is_dump = is_dump n_quota",
"2 self.quota = [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota",
"{ ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, {",
"player vs player player_choice: int -> Could be 0 or 1 (only needed",
"bin file \"\"\" def __init__( self, row: int, col: int, game_type: int, player_choice:",
"-> game configuration for game type, could be bot vs bot, player vs",
"vs bot) is_dump: bool -> is model loaded from bin file \"\"\" def",
"col: int, game_type: int, player_choice: int, is_dump: bool, thinking_time: float, ): self.row =",
"bool -> is model loaded from bin file \"\"\" def __init__( self, row:",
"shape col: int -> boards configuration column shape game_type: int (Look at GameConstant",
"type, could be bot vs bot, player vs bot, and player vs player",
"player_choice: int -> Could be 0 or 1 (only needed for player vs",
"n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type =",
"int -> boards configuration column shape game_type: int (Look at GameConstant for available",
"}, ] self.game_type = game_type self.player_choice = player_choice # 0 or 1 if",
"ShapeConstant class Config: \"\"\" Class representation for configuration needed in game [ATTRIBUTES] row:",
"// 2), }, { ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota //",
"== None: self.player_choice = -1 self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n'",
"player vs bot, and player vs player player_choice: int -> Could be 0",
"f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret += f'thinking_time:",
"n_quota - (n_quota // 2), }, { ShapeConstant.CROSS: n_quota - (n_quota // 2),",
"f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice:",
"// 2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type = game_type self.player_choice =",
"None: self.player_choice = -1 self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n' ret",
"bot, and player vs player player_choice: int -> Could be 0 or 1",
"= -1 self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n' ret += f'cow:",
"needed for player vs bot) thinking_time: float -> Maximal time for bot to",
"game type, could be bot vs bot, player vs bot, and player vs",
"Maximal time for bot to think (only needed for player vs bot or",
"{self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n'",
"needed for player vs bot or bot vs bot) is_dump: bool -> is",
"in game [ATTRIBUTES] row: int -> boards configuration row shape col: int ->",
"configuration column shape game_type: int (Look at GameConstant for available type) -> game",
"think (only needed for player vs bot or bot vs bot) is_dump: bool",
"int, col: int, game_type: int, player_choice: int, is_dump: bool, thinking_time: float, ): self.row",
"player vs bot or bot vs bot) is_dump: bool -> is model loaded",
"self.col = col self.is_dump = is_dump n_quota = row * col / 2",
"loaded from bin file \"\"\" def __init__( self, row: int, col: int, game_type:",
"n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, { ShapeConstant.CROSS: n_quota",
"for player vs bot or bot vs bot) is_dump: bool -> is model",
"- (n_quota // 2), }, { ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE:",
"game_type self.player_choice = player_choice # 0 or 1 if self.player_choice == None: self.player_choice",
"bool, thinking_time: float, ): self.row = row self.col = col self.is_dump = is_dump",
"vs bot, and player vs player player_choice: int -> Could be 0 or",
"(Look at GameConstant for available type) -> game configuration for game type, could",
"/ 2 self.quota = [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota -",
"player_choice # 0 or 1 if self.player_choice == None: self.player_choice = -1 self.thinking_time",
"or 1 if self.player_choice == None: self.player_choice = -1 self.thinking_time = thinking_time def",
"bot vs bot, player vs bot, and player vs player player_choice: int ->",
"int -> Could be 0 or 1 (only needed for player vs bot)",
"is_dump n_quota = row * col / 2 self.quota = [ { ShapeConstant.CROSS:",
"= [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2),",
"{self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret += f'thinking_time: {self.thinking_time}\\n'",
"= thinking_time def __str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret +=",
"-> boards configuration column shape game_type: int (Look at GameConstant for available type)",
"import ShapeConstant class Config: \"\"\" Class representation for configuration needed in game [ATTRIBUTES]",
"[ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), },",
"// 2, }, ] self.game_type = game_type self.player_choice = player_choice # 0 or",
"2, }, ] self.game_type = game_type self.player_choice = player_choice # 0 or 1",
"bot) is_dump: bool -> is model loaded from bin file \"\"\" def __init__(",
"+= f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret += f'thinking_time: {self.thinking_time}\\n' return ret",
"Could be 0 or 1 (only needed for player vs bot) thinking_time: float",
"* col / 2 self.quota = [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE:",
"ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type",
"self.player_choice = -1 self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n' ret +=",
"configuration row shape col: int -> boards configuration column shape game_type: int (Look",
"could be bot vs bot, player vs bot, and player vs player player_choice:",
"player_choice: int, is_dump: bool, thinking_time: float, ): self.row = row self.col = col",
"n_quota // 2, }, ] self.game_type = game_type self.player_choice = player_choice # 0",
"def __init__( self, row: int, col: int, game_type: int, player_choice: int, is_dump: bool,",
"= row self.col = col self.is_dump = is_dump n_quota = row * col",
"float -> Maximal time for bot to think (only needed for player vs",
"# 0 or 1 if self.player_choice == None: self.player_choice = -1 self.thinking_time =",
"__str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret",
"is model loaded from bin file \"\"\" def __init__( self, row: int, col:",
"col self.is_dump = is_dump n_quota = row * col / 2 self.quota =",
"- (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type = game_type",
"= game_type self.player_choice = player_choice # 0 or 1 if self.player_choice == None:",
"+= f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret +=",
"for available type) -> game configuration for game type, could be bot vs",
"): self.row = row self.col = col self.is_dump = is_dump n_quota = row",
"self.player_choice == None: self.player_choice = -1 self.thinking_time = thinking_time def __str__(self): ret =",
"player player_choice: int -> Could be 0 or 1 (only needed for player",
"ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret",
"row self.col = col self.is_dump = is_dump n_quota = row * col /",
"self, row: int, col: int, game_type: int, player_choice: int, is_dump: bool, thinking_time: float,",
"game_type: int, player_choice: int, is_dump: bool, thinking_time: float, ): self.row = row self.col",
"-1 self.thinking_time = thinking_time def __str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n'",
"self.is_dump = is_dump n_quota = row * col / 2 self.quota = [",
"class Config: \"\"\" Class representation for configuration needed in game [ATTRIBUTES] row: int",
"self.quota = [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota - (n_quota //",
"2, ShapeConstant.CIRCLE: n_quota - (n_quota // 2), }, { ShapeConstant.CROSS: n_quota - (n_quota",
"is_dump: bool, thinking_time: float, ): self.row = row self.col = col self.is_dump =",
"-> Maximal time for bot to think (only needed for player vs bot",
"col / 2 self.quota = [ { ShapeConstant.CROSS: n_quota // 2, ShapeConstant.CIRCLE: n_quota",
"be 0 or 1 (only needed for player vs bot) thinking_time: float ->",
"'[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n'",
"-> Could be 0 or 1 (only needed for player vs bot) thinking_time:",
"ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret +=",
"from bin file \"\"\" def __init__( self, row: int, col: int, game_type: int,",
"Class representation for configuration needed in game [ATTRIBUTES] row: int -> boards configuration",
"for game type, could be bot vs bot, player vs bot, and player",
"<filename>src/model/config.py<gh_stars>0 from src.constant import ShapeConstant class Config: \"\"\" Class representation for configuration needed",
"thinking_time: float -> Maximal time for bot to think (only needed for player",
"needed in game [ATTRIBUTES] row: int -> boards configuration row shape col: int",
"column shape game_type: int (Look at GameConstant for available type) -> game configuration",
"time for bot to think (only needed for player vs bot or bot",
"-> is model loaded from bin file \"\"\" def __init__( self, row: int,",
"representation for configuration needed in game [ATTRIBUTES] row: int -> boards configuration row",
"ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret += f'player_choice: {self.player_choice}\\n' ret",
"thinking_time def __str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol:",
"for configuration needed in game [ATTRIBUTES] row: int -> boards configuration row shape",
"bot, player vs bot, and player vs player player_choice: int -> Could be",
"= is_dump n_quota = row * col / 2 self.quota = [ {",
"src.constant import ShapeConstant class Config: \"\"\" Class representation for configuration needed in game",
"n_quota = row * col / 2 self.quota = [ { ShapeConstant.CROSS: n_quota",
"col: int -> boards configuration column shape game_type: int (Look at GameConstant for",
"] self.game_type = game_type self.player_choice = player_choice # 0 or 1 if self.player_choice",
"game_type: int (Look at GameConstant for available type) -> game configuration for game",
"available type) -> game configuration for game type, could be bot vs bot,",
"0 or 1 if self.player_choice == None: self.player_choice = -1 self.thinking_time = thinking_time",
"game [ATTRIBUTES] row: int -> boards configuration row shape col: int -> boards",
"vs bot, player vs bot, and player vs player player_choice: int -> Could",
"int, is_dump: bool, thinking_time: float, ): self.row = row self.col = col self.is_dump",
"vs player player_choice: int -> Could be 0 or 1 (only needed for",
"row shape col: int -> boards configuration column shape game_type: int (Look at",
"row * col / 2 self.quota = [ { ShapeConstant.CROSS: n_quota // 2,",
"= col self.is_dump = is_dump n_quota = row * col / 2 self.quota",
"int, game_type: int, player_choice: int, is_dump: bool, thinking_time: float, ): self.row = row",
"int, player_choice: int, is_dump: bool, thinking_time: float, ): self.row = row self.col =",
"2), }, { ShapeConstant.CROSS: n_quota - (n_quota // 2), ShapeConstant.CIRCLE: n_quota // 2,",
"vs bot or bot vs bot) is_dump: bool -> is model loaded from",
"to think (only needed for player vs bot or bot vs bot) is_dump:",
"(only needed for player vs bot) thinking_time: float -> Maximal time for bot",
"configuration needed in game [ATTRIBUTES] row: int -> boards configuration row shape col:",
"int -> boards configuration row shape col: int -> boards configuration column shape",
"model loaded from bin file \"\"\" def __init__( self, row: int, col: int,",
"self.player_choice = player_choice # 0 or 1 if self.player_choice == None: self.player_choice =",
"Config: \"\"\" Class representation for configuration needed in game [ATTRIBUTES] row: int ->",
"def __str__(self): ret = '[Configuration]\\n' ret += f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n'",
"ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret += f'game_type: {self.game_type}\\n' ret",
"= row * col / 2 self.quota = [ { ShapeConstant.CROSS: n_quota //",
"boards configuration column shape game_type: int (Look at GameConstant for available type) ->",
"1 (only needed for player vs bot) thinking_time: float -> Maximal time for",
"self.row = row self.col = col self.is_dump = is_dump n_quota = row *",
"row: int, col: int, game_type: int, player_choice: int, is_dump: bool, thinking_time: float, ):",
"shape game_type: int (Look at GameConstant for available type) -> game configuration for",
"at GameConstant for available type) -> game configuration for game type, could be",
"configuration for game type, could be bot vs bot, player vs bot, and",
"ShapeConstant.CIRCLE: n_quota // 2, }, ] self.game_type = game_type self.player_choice = player_choice #",
"+= f'cow: {self.row}\\n' ret += f'rol: {self.col}\\n' ret += f'is_dump: {self.is_dump}\\n' ret +=",
"or bot vs bot) is_dump: bool -> is model loaded from bin file"
] |
[
"Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not listing: return",
"listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i",
"has_more = len(comments) >= 20 offset = None if comments: offset = comments[-1]._id",
"Response(status=404) data = request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\")",
"listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user = request.user data =",
"= {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i in comments],",
"comments = list(listing_comments) has_more = len(comments) >= 20 offset = None if comments:",
"zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView):",
"user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def",
"Response, request from utils import json_encode from flask.views import MethodView from models.listings import",
"@authorize def post(self): user = request.user data = request.json text = data.get(\"text\") owner",
".all() comments = list(listing_comments) has_more = len(comments) >= 20 offset = None if",
"data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent, listing=listing.serialize(), owner=owner) comment.save() return Response(status=201)",
"for i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user =",
"Listing, ListingComment from auth import authorize class ListingsView(MethodView): @authorize def get(self): zipcode =",
"offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i in comments], \"meta\": meta}",
"post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data = request.json",
"Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings) >=",
".sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings) >= 20 offset = None",
"= request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not zipcode:",
"comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if",
"<filename>api/listings.py import datetime from bson import ObjectId from flask import Response, request from",
"listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self,",
"= list(listing_comments) has_more = len(comments) >= 20 offset = None if comments: offset",
"= data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent, listing=listing.serialize(),",
"return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit =",
"20 offset = None if listings: offset = listings[-1]._id meta = {\"next_offset\": offset,",
"= request.user data = request.json text = data.get(\"text\") owner = request.user.serialize() zipcode =",
"offset = None if comments: offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\":",
"None if listings: offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body",
"json_encode from flask.views import MethodView from models.listings import Listing, ListingComment from auth import",
"Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing",
"request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings =",
"response_body = {\"listings\": [i.serialize() for i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize",
"ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments) >= 20",
"= comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for",
"= Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not listing:",
"{\"comments\": [i.serialize() for i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self,",
"= Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings)",
"listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not",
"data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save()",
"offset = request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\":",
"return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return",
"limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not zipcode: return Response(status=400)",
"ListingComment from auth import authorize class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode",
"response_body = {\"comments\": [i.serialize() for i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize",
"offset = None if listings: offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\":",
"@authorize def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\",",
"20) offset = request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments = ListingComment.q.filter(",
"{\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i in comments], \"meta\":",
"data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text,",
"i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing =",
"comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i",
"def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0)",
"= len(listings) >= 20 offset = None if listings: offset = listings[-1]._id meta",
"request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class",
"for i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing",
"is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent,",
"utils import json_encode from flask.views import MethodView from models.listings import Listing, ListingComment from",
"meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i in",
"= Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data = request.json text = data.get(\"text\")",
"flask.views import MethodView from models.listings import Listing, ListingComment from auth import authorize class",
"import Listing, ListingComment from auth import authorize class ListingsView(MethodView): @authorize def get(self): zipcode",
"{\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i in listings], \"meta\":",
"def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\",",
"\"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user = request.user data = request.json",
"Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data = request.json text = data.get(\"text\") is_private",
"return Response(status=404) data = request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent =",
"\"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i in comments], \"meta\": meta} return",
"0) if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\",",
"= list(listings) has_more = len(listings) >= 20 offset = None if listings: offset",
"= data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent, listing=listing.serialize(), owner=owner) comment.save() return",
"not listing: return Response(status=404) data = request.json text = data.get(\"text\") is_private = data.get(\"is_private\")",
"import Response, request from utils import json_encode from flask.views import MethodView from models.listings",
"return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings)",
"data = request.json text = data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing",
".skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments) >= 20 offset",
"request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments =",
"= {\"listings\": [i.serialize() for i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def",
"user = request.user data = request.json text = data.get(\"text\") owner = request.user.serialize() zipcode",
"def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data =",
"zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings) >= 20",
"offset = request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\",
"= listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for",
"from utils import json_encode from flask.views import MethodView from models.listings import Listing, ListingComment",
"request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\",
"Response(json_encode(response_body)) @authorize def post(self): user = request.user data = request.json text = data.get(\"text\")",
"import datetime from bson import ObjectId from flask import Response, request from utils",
"[i.serialize() for i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user",
"has_more} response_body = {\"comments\": [i.serialize() for i in comments], \"meta\": meta} return Response(json_encode(response_body))",
"comments: offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\":",
"has_more} response_body = {\"listings\": [i.serialize() for i in listings], \"meta\": meta} return Response(json_encode(response_body))",
"in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user = request.user data",
"ObjectId from flask import Response, request from utils import json_encode from flask.views import",
"listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit",
"meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing:",
"listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data = request.json text",
"offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i in listings], \"meta\": meta}",
"= Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id):",
"listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data = request.json text =",
"= None if comments: offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more}",
"listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more",
"len(comments) >= 20 offset = None if comments: offset = comments[-1]._id meta =",
".limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments) >= 20 offset = None",
"request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not zipcode: return",
"zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not",
"get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if",
"import ObjectId from flask import Response, request from utils import json_encode from flask.views",
"len(listings) >= 20 offset = None if listings: offset = listings[-1]._id meta =",
"*CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset",
"= ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more =",
"list(listing_comments) has_more = len(comments) >= 20 offset = None if comments: offset =",
"data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent, listing=listing.serialize(), owner=owner)",
"from auth import authorize class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit",
"import MethodView from models.listings import Listing, ListingComment from auth import authorize class ListingsView(MethodView):",
"{\"listings\": [i.serialize() for i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self):",
"None if comments: offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body",
">= 20 offset = None if listings: offset = listings[-1]._id meta = {\"next_offset\":",
"request from utils import json_encode from flask.views import MethodView from models.listings import Listing,",
"text = data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner,",
"= user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize",
"request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\",
"authorize class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20)",
"listing: return Response(status=404) data = request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent",
"if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all()",
"meta} return Response(json_encode(response_body)) @authorize def post(self): user = request.user data = request.json text",
"has_more = len(listings) >= 20 offset = None if listings: offset = listings[-1]._id",
"@authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset =",
"def post(self): user = request.user data = request.json text = data.get(\"text\") owner =",
"owner=owner, zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing =",
"{\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments) >=",
"auth import authorize class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit =",
".limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings) >= 20 offset =",
"bson import ObjectId from flask import Response, request from utils import json_encode from",
"= request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return Response(status=201)",
">= 20 offset = None if comments: offset = comments[-1]._id meta = {\"next_offset\":",
"= {\"comments\": [i.serialize() for i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def",
"= request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner =",
"0) if not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\",
"if not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\",
"meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize() for i in",
"= len(comments) >= 20 offset = None if comments: offset = comments[-1]._id meta",
"return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments =",
"in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id))",
"request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize()",
"listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more =",
"= data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode)",
"limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not listing: return Response(status=404)",
"= request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\",
"Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404)",
"if comments: offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body =",
"= data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment =",
"request.user data = request.json text = data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode",
"Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\",",
"models.listings import Listing, ListingComment from auth import authorize class ListingsView(MethodView): @authorize def get(self):",
"data = request.json text = data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner",
"import authorize class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\",",
"20 offset = None if comments: offset = comments[-1]._id meta = {\"next_offset\": offset,",
"[i.serialize() for i in comments], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id):",
"get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0)",
"= request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not listing: return Response(status=404) listing_comments",
"from models.listings import Listing, ListingComment from auth import authorize class ListingsView(MethodView): @authorize def",
"i in listings], \"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self): user = request.user",
"from bson import ObjectId from flask import Response, request from utils import json_encode",
"class ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset",
"text = data.get(\"text\") is_private = data.get(\"is_private\") parent = data.get(\"parent\") owner = request.user.serialize() comment",
"\"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i in listings], \"meta\": meta} return",
"= request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings",
"zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings =",
"Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more",
"flask import Response, request from utils import json_encode from flask.views import MethodView from",
"zipcode=zipcode) listing.save() return Response(status=201) class *CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id))",
"@authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not listing: return Response(status=404) data",
"datetime from bson import ObjectId from flask import Response, request from utils import",
"from flask.views import MethodView from models.listings import Listing, ListingComment from auth import authorize",
"Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments)",
"offset = comments[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"comments\": [i.serialize()",
"\"meta\": meta} return Response(json_encode(response_body)) @authorize def post(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) if not",
".sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments) >= 20 offset =",
"= request.json text = data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing =",
"class *CommentListView(MethodView): @authorize def get(self, listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20)",
"-1).all() listings = list(listings) has_more = len(listings) >= 20 offset = None if",
"ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments = list(listing_comments) has_more = len(comments)",
"return Response(json_encode(response_body)) @authorize def post(self): user = request.user data = request.json text =",
"listing_id): listing = Listing.q.get(_id=ObjectId(listing_id)) limit = request.args.get(\"limit\", 20) offset = request.args.get(\"offset\", 0) if",
"= None if listings: offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more}",
"offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize()",
"not listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all()",
"if not listing: return Response(status=404) data = request.json text = data.get(\"text\") is_private =",
"listing: return Response(status=404) listing_comments = ListingComment.q.filter( {\"listing.id\": ObjectId(listing_id)})\\ .skip(offset)\\ .sort(\"-created_at\")\\ .limit(limit)\\ .all() comments",
"import json_encode from flask.views import MethodView from models.listings import Listing, ListingComment from auth",
"ListingsView(MethodView): @authorize def get(self): zipcode = request.user.zipcode limit = request.args.get(\"limit\", 20) offset =",
"parent = data.get(\"parent\") owner = request.user.serialize() comment = ListingComment(text=text, parent=parent, listing=listing.serialize(), owner=owner) comment.save()",
"not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings",
"request.json text = data.get(\"text\") owner = request.user.serialize() zipcode = user.zipcode listing = Listing(text=text,",
".skip(offset)\\ .limit(limit)\\ .sort(\"created_at\", -1).all() listings = list(listings) has_more = len(listings) >= 20 offset",
"post(self): user = request.user data = request.json text = data.get(\"text\") owner = request.user.serialize()",
"from flask import Response, request from utils import json_encode from flask.views import MethodView",
"= request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\": zipcode})\\ .skip(offset)\\",
"listings = list(listings) has_more = len(listings) >= 20 offset = None if listings:",
"list(listings) has_more = len(listings) >= 20 offset = None if listings: offset =",
"owner = request.user.serialize() zipcode = user.zipcode listing = Listing(text=text, owner=owner, zipcode=zipcode) listing.save() return",
"if listings: offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body =",
"= {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\": [i.serialize() for i in listings],",
"20) offset = request.args.get(\"offset\", 0) if not zipcode: return Response(status=400) listings = Listing.q.filter({\"zipcode\":",
"listings: offset = listings[-1]._id meta = {\"next_offset\": offset, \"has_more\": has_more} response_body = {\"listings\":",
"MethodView from models.listings import Listing, ListingComment from auth import authorize class ListingsView(MethodView): @authorize"
] |
[
"- Guess Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution:",
"n: int) -> int: lo = 0 hi = n while lo <=",
"= n while lo <= hi: mid = (hi + lo) // 2",
"// 2 res = guess(mid) if res == 0: return mid elif res",
"class Solution: def guessNumber(self, n: int) -> int: lo = 0 hi =",
"Guess Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def",
"or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int)",
"lo <= hi: mid = (hi + lo) // 2 res = guess(mid)",
"Problem: 374 - Guess Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\"",
"hi: mid = (hi + lo) // 2 res = guess(mid) if res",
"lo = 0 hi = n while lo <= hi: mid = (hi",
"https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int) -> int: lo = 0",
"== 0: return mid elif res > 0: lo = mid + 1",
"Solution: def guessNumber(self, n: int) -> int: lo = 0 hi = n",
"0 hi = n while lo <= hi: mid = (hi + lo)",
"Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int) -> int: lo",
"= guess(mid) if res == 0: return mid elif res > 0: lo",
"mid = (hi + lo) // 2 res = guess(mid) if res ==",
"(hi + lo) // 2 res = guess(mid) if res == 0: return",
"lo = mid + 1 else: hi = mid - 1 return -1",
"lo) // 2 res = guess(mid) if res == 0: return mid elif",
"374 - Guess Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class",
"Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self,",
"Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int) ->",
"hi = n while lo <= hi: mid = (hi + lo) //",
"Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int) -> int:",
"guessNumber(self, n: int) -> int: lo = 0 hi = n while lo",
"res = guess(mid) if res == 0: return mid elif res > 0:",
"URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n: int) -> int: lo =",
"mid elif res > 0: lo = mid + 1 else: hi =",
"def guessNumber(self, n: int) -> int: lo = 0 hi = n while",
"+ lo) // 2 res = guess(mid) if res == 0: return mid",
"while lo <= hi: mid = (hi + lo) // 2 res =",
"elif res > 0: lo = mid + 1 else: hi = mid",
"if res == 0: return mid elif res > 0: lo = mid",
"\"\"\" Problem: 374 - Guess Number Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/",
"return mid elif res > 0: lo = mid + 1 else: hi",
"res == 0: return mid elif res > 0: lo = mid +",
"<= hi: mid = (hi + lo) // 2 res = guess(mid) if",
"> 0: lo = mid + 1 else: hi = mid - 1",
"0: lo = mid + 1 else: hi = mid - 1 return",
"\"\"\" class Solution: def guessNumber(self, n: int) -> int: lo = 0 hi",
"= 0 hi = n while lo <= hi: mid = (hi +",
"Higher or Lower Difficulty: Easy URL: https://leetcode.com/problems/guess-number-higher-or-lower/ \"\"\" class Solution: def guessNumber(self, n:",
"-> int: lo = 0 hi = n while lo <= hi: mid",
"int: lo = 0 hi = n while lo <= hi: mid =",
"= (hi + lo) // 2 res = guess(mid) if res == 0:",
"guess(mid) if res == 0: return mid elif res > 0: lo =",
"2 res = guess(mid) if res == 0: return mid elif res >",
"n while lo <= hi: mid = (hi + lo) // 2 res",
"int) -> int: lo = 0 hi = n while lo <= hi:",
"0: return mid elif res > 0: lo = mid + 1 else:",
"res > 0: lo = mid + 1 else: hi = mid -",
"<reponame>mmore21/competitive<filename>leetcode/e_374.py \"\"\" Problem: 374 - Guess Number Higher or Lower Difficulty: Easy URL:"
] |
[
"else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2)",
"# except StopIteration: # self.cur_char = None def generate_tokens(self): while self.cur_char is not",
"# self.cur_char = next(self.text) # except StopIteration: # self.cur_char = None def generate_tokens(self):",
"= self.cur_char self.advance() while self.cur_char is not None and (self.cur_char == \".\" or",
"Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance()",
"# (1 + 2) * 3 # # * # / \\ #",
"while self.cur_char is not None and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char",
"self.cur_char is not None and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char ==",
"# self.cur_char = None def generate_tokens(self): while self.cur_char is not None: if self.cur_char",
"+ # / \\ # a * # / \\ # b c",
"self.cur_char in whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif",
"\" \\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self, code): self.source = code",
"if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1 + 2 *",
"# def advance(self): # try: # self.cur_char = next(self.text) # except StopIteration: #",
"+= self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"): number_str",
"self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char ==",
"self.cur_char = None def generate_tokens(self): while self.cur_char is not None: if self.cur_char in",
"\"0123456789\" class Lexer: def __init__(self, code): self.source = code + '\\n' self.cur_char =",
"self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos += pos try: self.cur_char =",
"\\ # a * # / \\ # b c # (1 +",
"self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2) yield",
"/ \\ # b c # (1 + 2) * 3 # #",
"digits = \"0123456789\" class Lexer: def __init__(self, code): self.source = code + '\\n'",
"self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char ==",
"self.cur_char = None self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos += pos",
"self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def peek(self): try: return self.source[self.cur_pos +",
"\"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char",
"'0' return Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3 # # +",
"code): self.source = code + '\\n' self.cur_char = None self.cur_pos = -1 self.advance()",
"pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def",
"= None self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos += pos try:",
"== \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\":",
"+= '0' return Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3 # #",
"1 + 2 * 3 # # + # / \\ # a",
"\"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance()",
"or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char",
"# a * # / \\ # b c # (1 + 2)",
"if decimal_point_count > 1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str =",
"elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance()",
"# / \\ # a * # / \\ # b c #",
"yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\":",
"try: # self.cur_char = next(self.text) # except StopIteration: # self.cur_char = None def",
"'{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance() while self.cur_char is",
"== \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif",
"Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if",
"self.source[self.cur_pos + 1] except: return None # def advance(self): # try: # self.cur_char",
"if self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count > 1: break number_str",
"Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str =",
"1] except: return None # def advance(self): # try: # self.cur_char = next(self.text)",
"def generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance() while self.cur_char is not",
"== \".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count",
"# + # / \\ # a * # / \\ # b",
"# try: # self.cur_char = next(self.text) # except StopIteration: # self.cur_char = None",
"self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char ==",
"except: return None # def advance(self): # try: # self.cur_char = next(self.text) #",
"or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count > 1:",
"Lexer: def __init__(self, code): self.source = code + '\\n' self.cur_char = None self.cur_pos",
"= code + '\\n' self.cur_char = None self.cur_pos = -1 self.advance() def advance(self,",
"self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield",
"== \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else:",
"elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def",
"None def generate_tokens(self): while self.cur_char is not None: if self.cur_char in whitespace: self.advance()",
"yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token)",
"self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token)",
"self.source = code + '\\n' self.cur_char = None self.cur_pos = -1 self.advance() def",
"self.cur_char = None def peek(self): try: return self.source[self.cur_pos + 1] except: return None",
"None # def advance(self): # try: # self.cur_char = next(self.text) # except StopIteration:",
"== \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif",
"whitespace = \" \\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self, code): self.source",
"except StopIteration: # self.cur_char = None def generate_tokens(self): while self.cur_char is not None:",
"= -1 self.advance() def advance(self, pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos]",
"tokens import Token, TokenType whitespace = \" \\n\\t\" digits = \"0123456789\" class Lexer:",
"c # (1 + 2) * 3 # # * # / \\",
"3 # # * # / \\ # + c # / \\",
"self.advance() def advance(self, pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char",
"= None def peek(self): try: return self.source[self.cur_pos + 1] except: return None #",
"\"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if",
"elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield",
"self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() ==",
"def generate_tokens(self): while self.cur_char is not None: if self.cur_char in whitespace: self.advance() elif",
"= next(self.text) # except StopIteration: # self.cur_char = None def generate_tokens(self): while self.cur_char",
"'0' + number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1",
"if self.cur_char in whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number()",
"== \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif",
"Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3 # # + # /",
"if number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"): number_str += '0' return",
"elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek()",
"in whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char",
"Token, TokenType whitespace = \" \\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self,",
"self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"): number_str += '0'",
"# 1 + 2 * 3 # # + # / \\ #",
"1 if decimal_point_count > 1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str",
"(1 + 2) * 3 # # * # / \\ # +",
"self.source[self.cur_pos] except: self.cur_char = None def peek(self): try: return self.source[self.cur_pos + 1] except:",
"self.cur_char = next(self.text) # except StopIteration: # self.cur_char = None def generate_tokens(self): while",
"self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count > 1: break",
"self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance()",
"self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield",
"yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token)",
"+ number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1 +",
"self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal",
"self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"): number_str +=",
"== \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token)",
"Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() == \"/\":",
"yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character",
"elif self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance()",
"character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance() while self.cur_char",
"'\\n' self.cur_char = None self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos +=",
"number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"):",
"self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char ==",
"class Lexer: def __init__(self, code): self.source = code + '\\n' self.cur_char = None",
"while self.cur_char is not None: if self.cur_char in whitespace: self.advance() elif self.cur_char ==",
"+ 1] except: return None # def advance(self): # try: # self.cur_char =",
"\".\": decimal_point_count += 1 if decimal_point_count > 1: break number_str += self.cur_char self.advance()",
"# b c # (1 + 2) * 3 # # * #",
"TokenType whitespace = \" \\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self, code):",
"Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else:",
"-1 self.advance() def advance(self, pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except:",
"== \"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token)",
"self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char ==",
"try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def peek(self): try: return self.source[self.cur_pos",
"number_str = '0' + number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str))",
"None def peek(self): try: return self.source[self.cur_pos + 1] except: return None # def",
"not None: if self.cur_char in whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit():",
"whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char ==",
"yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\":",
"self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char ==",
"and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1",
"else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char",
"+ '\\n' self.cur_char = None self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos",
"> 1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' +",
"* 3 # # * # / \\ # + c # /",
"if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char",
"yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\":",
"Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance()",
"self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0",
"= '0' + number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) #",
"/ \\ # a * # / \\ # b c # (1",
"yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek() ==",
"\"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif",
"code + '\\n' self.cur_char = None self.cur_pos = -1 self.advance() def advance(self, pos=1):",
"generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance() while self.cur_char is not None",
"+= 1 if decimal_point_count > 1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"):",
"decimal_point_count > 1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0'",
"number_str = self.cur_char self.advance() while self.cur_char is not None and (self.cur_char == \".\"",
"1: break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str",
"Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\")",
"self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self):",
"raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance()",
"+= pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def peek(self): try:",
"* # / \\ # b c # (1 + 2) * 3",
"not None and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count",
"self.cur_char == \")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token)",
"== \"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count",
"# # * # / \\ # + c # / \\ #",
"def __init__(self, code): self.source = code + '\\n' self.cur_char = None self.cur_pos =",
"None self.cur_pos = -1 self.advance() def advance(self, pos=1): self.cur_pos += pos try: self.cur_char",
"peek(self): try: return self.source[self.cur_pos + 1] except: return None # def advance(self): #",
"return None # def advance(self): # try: # self.cur_char = next(self.text) # except",
"== \"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token)",
"2 * 3 # # + # / \\ # a * #",
"None and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count +=",
"== \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() == \"*\":",
"def advance(self, pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char =",
"= 0 number_str = self.cur_char self.advance() while self.cur_char is not None and (self.cur_char",
"return Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3 # # + #",
"* # / \\ # + c # / \\ # a b",
"= self.source[self.cur_pos] except: self.cur_char = None def peek(self): try: return self.source[self.cur_pos + 1]",
"if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char",
"# / \\ # b c # (1 + 2) * 3 #",
"pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def peek(self): try: return",
"__init__(self, code): self.source = code + '\\n' self.cur_char = None self.cur_pos = -1",
"self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token)",
"self.advance() while self.cur_char is not None and (self.cur_char == \".\" or self.cur_char.isdigit()): if",
"= \" \\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self, code): self.source =",
"yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\":",
"def peek(self): try: return self.source[self.cur_pos + 1] except: return None # def advance(self):",
"self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif self.cur_char == \"/\": if self.peek()",
"(self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1 if",
"elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield",
"\"%\": self.advance() yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count =",
"self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\":",
"number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3",
"except: self.cur_char = None def peek(self): try: return self.source[self.cur_pos + 1] except: return",
"is not None: if self.cur_char in whitespace: self.advance() elif self.cur_char == \".\" or",
"break number_str += self.cur_char self.advance() if number_str.startswith(\".\"): number_str = '0' + number_str if",
"Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance()",
"self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None def peek(self):",
"self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2) yield",
"self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char ==",
"\")\": self.advance() yield Token(TokenType.right_parentheses_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) else: raise",
"\".\" or self.cur_char.isdigit()): if self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count >",
"elif self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance()",
"b c # (1 + 2) * 3 # # * # /",
"decimal_point_count = 0 number_str = self.cur_char self.advance() while self.cur_char is not None and",
"import Token, TokenType whitespace = \" \\n\\t\" digits = \"0123456789\" class Lexer: def",
"\".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield Token(TokenType.plus_token) elif",
"def advance(self): # try: # self.cur_char = next(self.text) # except StopIteration: # self.cur_char",
"yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\":",
"advance(self, pos=1): self.cur_pos += pos try: self.cur_char = self.source[self.cur_pos] except: self.cur_char = None",
"= None def generate_tokens(self): while self.cur_char is not None: if self.cur_char in whitespace:",
"elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif self.cur_char == \")\": self.advance() yield",
"else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str = self.cur_char",
"is not None and (self.cur_char == \".\" or self.cur_char.isdigit()): if self.cur_char == \".\":",
"== \".\": decimal_point_count += 1 if decimal_point_count > 1: break number_str += self.cur_char",
"advance(self): # try: # self.cur_char = next(self.text) # except StopIteration: # self.cur_char =",
"yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token)",
"float(number_str)) # 1 + 2 * 3 # # + # / \\",
"+ 2 * 3 # # + # / \\ # a *",
"\"+\": self.advance() yield Token(TokenType.plus_token) elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char",
"* 3 # # + # / \\ # a * # /",
"= \"0123456789\" class Lexer: def __init__(self, code): self.source = code + '\\n' self.cur_char",
"0 number_str = self.cur_char self.advance() while self.cur_char is not None and (self.cur_char ==",
"self.cur_char self.advance() while self.cur_char is not None and (self.cur_char == \".\" or self.cur_char.isdigit()):",
"Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else:",
"try: return self.source[self.cur_pos + 1] except: return None # def advance(self): # try:",
"\\ # b c # (1 + 2) * 3 # # *",
"a * # / \\ # b c # (1 + 2) *",
"== \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\":",
"\"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char",
"self.cur_char is not None: if self.cur_char in whitespace: self.advance() elif self.cur_char == \".\"",
"yield Token(TokenType.percent_token) else: raise Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str",
"next(self.text) # except StopIteration: # self.cur_char = None def generate_tokens(self): while self.cur_char is",
"2) * 3 # # * # / \\ # + c #",
"\"%\": self.advance() yield Token(TokenType.percent_token) elif self.cur_char == \"*\": if self.peek() == \"*\": self.advance(2)",
"from tokens import Token, TokenType whitespace = \" \\n\\t\" digits = \"0123456789\" class",
"elif self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield",
"# * # / \\ # + c # / \\ # a",
"self.cur_char == \"-\": self.advance() yield Token(TokenType.minus_token) elif self.cur_char == \"%\": self.advance() yield Token(TokenType.percent_token)",
"None: if self.cur_char in whitespace: self.advance() elif self.cur_char == \".\" or self.cur_char.isdigit(): yield",
"return self.source[self.cur_pos + 1] except: return None # def advance(self): # try: #",
"self.cur_char == \"/\": if self.peek() == \"/\": self.advance(2) yield Token(TokenType.slash_slash_token) else: self.advance() yield",
"number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1 + 2 * 3 #",
"self.cur_char == \".\": decimal_point_count += 1 if decimal_point_count > 1: break number_str +=",
"3 # # + # / \\ # a * # / \\",
"self.cur_char == \".\" or self.cur_char.isdigit(): yield self.generate_number() elif self.cur_char == \"+\": self.advance() yield",
"\"*\": if self.peek() == \"*\": self.advance(2) yield Token(TokenType.star_star_token) else: self.advance() yield Token(TokenType.star_token) elif",
"Exception(f\"Illegal character '{self.cur_char}'\") def generate_number(self): decimal_point_count = 0 number_str = self.cur_char self.advance() while",
"number_str.startswith(\".\"): number_str = '0' + number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token,",
"decimal_point_count += 1 if decimal_point_count > 1: break number_str += self.cur_char self.advance() if",
"\\n\\t\" digits = \"0123456789\" class Lexer: def __init__(self, code): self.source = code +",
"number_str if number_str.endswith(\".\"): number_str += '0' return Token(TokenType.number_token, float(number_str)) # 1 + 2",
"# # + # / \\ # a * # / \\ #",
"Token(TokenType.slash_slash_token) else: self.advance() yield Token(TokenType.slash_token) elif self.cur_char == \"(\": self.advance() yield Token(TokenType.left_parentheses_token) elif",
"+ 2) * 3 # # * # / \\ # + c",
"generate_tokens(self): while self.cur_char is not None: if self.cur_char in whitespace: self.advance() elif self.cur_char",
"StopIteration: # self.cur_char = None def generate_tokens(self): while self.cur_char is not None: if"
] |
[
"if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep() print(\"e-Paper clear",
"sys import os libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd",
"import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep() print(\"e-Paper clear & sleep done.\")",
"import sys import os libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2",
"os libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD()",
"sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep() print(\"e-Paper clear & sleep",
"os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep() print(\"e-Paper clear &",
"import os libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd =",
"'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep() print(\"e-Paper",
"os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear() epd.sleep()",
"#!/usr/bin/python3 import sys import os libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import",
"= os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init() epd.Clear()",
"libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epd') if os.path.exists(libdir): sys.path.append(libdir) import epd7in5_V2 epd = epd7in5_V2.EPD() epd.init()"
] |
[
"= self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent",
"KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible",
"self._root = _root if _root else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io,",
"def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted =",
"self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0",
"stored = 0 compressed = 1 packed = 2 lzhed = 3 reserved_4",
"def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) -",
"= _parent self._root = _root if _root else self self._read() def _read(self): self.header",
"import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum",
"= 2 unix = 3 vm_cms = 4 atari_tos = 5 hpfs_filesystem =",
"BytesIO from enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct",
"z_system = 8 cpm = 9 tops_20 = 10 ntfs_filesystem = 11 qdos",
"if _root else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed",
"self._root = _root if _root else self self._read() def _read(self): self.magic = self._io.read_bytes(2)",
"if self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len =",
"True: self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name",
"import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version)",
"= 6 reserved_7 = 7 deflate = 8 class EnumOs(Enum): fat_filesystem = 0",
"from enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python",
"reserved_5 = 5 reserved_6 = 6 reserved_7 = 7 deflate = 8 class",
"10 ntfs_filesystem = 11 qdos = 12 acorn_riscos = 13 unknown = 255",
"8 cpm = 9 tops_20 = 10 ntfs_filesystem = 11 qdos = 12",
"self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True:",
"_read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8))",
"vms = 2 unix = 3 vm_cms = 4 atari_tos = 5 hpfs_filesystem",
"if self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes =",
"from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO",
"Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or",
"4 atari_tos = 5 hpfs_filesystem = 6 macintosh = 7 z_system = 8",
"= 1 vms = 2 unix = 3 vm_cms = 4 atari_tos =",
"4 reserved_5 = 5 reserved_6 = 6 reserved_7 = 7 deflate = 8",
"acorn_riscos = 13 unknown = 255 def __init__(self, _io, _parent=None, _root=None): self._io =",
"self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted",
"= _root if _root else self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method",
"parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later is",
"class EnumCompression(Enum): stored = 0 compressed = 1 packed = 2 lzhed =",
"self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name ==",
"fat_filesystem = 0 amiga = 1 vms = 2 unix = 3 vm_cms",
"class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent",
"and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__",
"self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le()",
"= self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) !=",
"self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0,",
"self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent =",
"< parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later is required,",
"1 packed = 2 lzhed = 3 reserved_4 = 4 reserved_5 = 5",
"6 reserved_7 = 7 deflate = 8 class EnumOs(Enum): fat_filesystem = 0 amiga",
"2 unix = 3 vm_cms = 4 atari_tos = 5 hpfs_filesystem = 6",
"_parent self._root = _root if _root else self self._read() def _read(self): self.header =",
"<reponame>naaya17/carpe # This is a generated file! Please edit source .ksy file and",
"# This is a generated file! Please edit source .ksy file and use",
"3 vm_cms = 4 atari_tos = 5 hpfs_filesystem = 6 macintosh = 7",
"EnumCompression(Enum): stored = 0 compressed = 1 packed = 2 lzhed = 3",
"= self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True:",
"self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le()",
"self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct):",
"self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len",
"(ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed = 1 packed =",
"1 vms = 2 unix = 3 vm_cms = 4 atari_tos = 5",
"= 1 packed = 2 lzhed = 3 reserved_4 = 4 reserved_5 =",
"8 class EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms = 2 unix",
"Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have",
".ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct",
"self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io",
"self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1)",
"== True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted == True: self.encryption_header",
"= self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le() if",
"_read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1)",
"= self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number",
"self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized =",
"= self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system =",
"a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild",
"self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len)",
"True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True,",
"self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32",
"or later is required, but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class",
"API: 0.7 or later is required, but you have %s\" % (ks_version)) class",
"amiga = 1 vms = 2 unix = 3 vm_cms = 4 atari_tos",
"= self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class",
"if _root else self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1())",
"later is required, but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum):",
"= 5 reserved_6 = 6 reserved_7 = 7 deflate = 8 class EnumOs(Enum):",
"fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed = 1 packed = 2 lzhed",
"self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) !=",
"self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1)",
"!= 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text",
"= 6 macintosh = 7 z_system = 8 cpm = 9 tops_20 =",
"= self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0",
"== True: self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le() if",
"= 7 deflate = 8 class EnumOs(Enum): fat_filesystem = 0 amiga = 1",
"self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0",
"self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self,",
"ntfs_filesystem = 11 qdos = 12 acorn_riscos = 13 unknown = 255 def",
"= self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1)",
"modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if",
"is required, but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored",
"self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() -",
"ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise",
"_io self._parent = _parent self._root = _root if _root else self self._read() def",
"- self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def",
"Kaitai Struct Python API: 0.7 or later is required, but you have %s\"",
"13 unknown = 255 def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent",
"self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted",
"self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) !=",
"Struct Python API: 0.7 or later is required, but you have %s\" %",
"Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import",
"if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted ==",
"required, but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored =",
"is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to",
"GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root",
"have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed =",
"= self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra == True:",
"= 11 qdos = 12 acorn_riscos = 13 unknown = 255 def __init__(self,",
"self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number =",
"from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum",
"= self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if",
"unix = 3 vm_cms = 4 atari_tos = 5 hpfs_filesystem = 6 macintosh",
"self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name =",
"0 compressed = 1 packed = 2 lzhed = 3 reserved_4 = 4",
"= 0 amiga = 1 vms = 2 unix = 3 vm_cms =",
"%s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed = 1",
"self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1())",
"12 acorn_riscos = 13 unknown = 255 def __init__(self, _io, _parent=None, _root=None): self._io",
"5 reserved_6 = 6 reserved_7 = 7 deflate = 8 class EnumOs(Enum): fat_filesystem",
"self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1)",
"= self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) !=",
"vm_cms = 4 atari_tos = 5 hpfs_filesystem = 6 macintosh = 7 z_system",
"else self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits =",
"reserved_6 = 6 reserved_7 = 7 deflate = 8 class EnumOs(Enum): fat_filesystem =",
"= 9 tops_20 = 10 ntfs_filesystem = 11 qdos = 12 acorn_riscos =",
"self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system",
"= 5 hpfs_filesystem = 6 macintosh = 7 z_system = 8 cpm =",
"def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root =",
"0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation",
"5 hpfs_filesystem = 6 macintosh = 7 z_system = 8 cpm = 9",
"= _io self._parent = _parent self._root = _root if _root else self self._read()",
"= _root if _root else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self,",
"9 tops_20 = 10 ntfs_filesystem = 11 qdos = 12 acorn_riscos = 13",
"self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name",
"2 lzhed = 3 reserved_4 = 4 reserved_5 = 5 reserved_6 = 6",
"pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from",
"7 deflate = 8 class EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms",
"True: self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra",
"= self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) !=",
"use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as",
"self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0",
"self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le()",
"= 13 unknown = 255 def __init__(self, _io, _parent=None, _root=None): self._io = _io",
"0 amiga = 1 vms = 2 unix = 3 vm_cms = 4",
"reserved_7 = 7 deflate = 8 class EnumOs(Enum): fat_filesystem = 0 amiga =",
"self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation ==",
"you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed",
"KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai",
"% (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed = 1 packed",
"as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version) < parse_version('0.7'):",
"import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7",
"= 2 lzhed = 3 reserved_4 = 4 reserved_5 = 5 reserved_6 =",
"self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1)",
"= 7 z_system = 8 cpm = 9 tops_20 = 10 ntfs_filesystem =",
"Python API: 0.7 or later is required, but you have %s\" % (ks_version))",
"class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0 compressed = 1 packed = 2",
"self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time =",
"self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le()",
"parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later is required, but",
"!= 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra",
"if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later",
"0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra =",
"lzhed = 3 reserved_4 = 4 reserved_5 = 5 reserved_6 = 6 reserved_7",
"!= 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte()",
"= 12 acorn_riscos = 13 unknown = 255 def __init__(self, _io, _parent=None, _root=None):",
"_parent self._root = _root if _root else self self._read() def _read(self): self.magic =",
"_root else self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits",
"= 255 def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent",
"0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text =",
"edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version",
"__version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(ks_version) <",
"self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra",
"tops_20 = 10 ntfs_filesystem = 11 qdos = 12 acorn_riscos = 13 unknown",
"= self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 =",
"= 3 reserved_4 = 4 reserved_5 = 5 reserved_6 = 6 reserved_7 =",
"- 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io,",
"enum import Enum if parse_version(ks_version) < parse_version('0.7'): raise Exception(\"Incompatible Kaitai Struct Python API:",
"6 macintosh = 7 z_system = 8 cpm = 9 tops_20 = 10",
"_io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if",
"= self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io",
"= self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le()",
"= 0 compressed = 1 packed = 2 lzhed = 3 reserved_4 =",
"self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos()) - 8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized",
"!= 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags =",
"= 10 ntfs_filesystem = 11 qdos = 12 acorn_riscos = 13 unknown =",
"= 8 cpm = 9 tops_20 = 10 ntfs_filesystem = 11 qdos =",
"compressed = 1 packed = 2 lzhed = 3 reserved_4 = 4 reserved_5",
"0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation =",
"self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io =",
"but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct): class EnumCompression(Enum): stored = 0",
"True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted == True: self.encryption_header =",
"= self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name",
"parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from enum import",
"_root else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed =",
"= 3 vm_cms = 4 atari_tos = 5 hpfs_filesystem = 6 macintosh =",
"self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes",
"if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name =",
"kaitai-struct-compiler to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version,",
"self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags",
"rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream,",
"self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None):",
"11 qdos = 12 acorn_riscos = 13 unknown = 255 def __init__(self, _io,",
"source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from",
"raise Exception(\"Incompatible Kaitai Struct Python API: 0.7 or later is required, but you",
"EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms = 2 unix = 3",
"self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2)",
"__init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root",
"_root if _root else self self._read() def _read(self): self.magic = self._io.read_bytes(2) self.compression_method =",
"8)) self.crc32 = self._io.read_u4le() self.uncompressed_sized = self._io.read_u4le() class GzipHeader(KaitaiStruct): def __init__(self, _io, _parent=None,",
"self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0",
"generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from",
"file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import",
"_root if _root else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root)",
"255 def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root",
"!= 0 self.flag_name = self._io.read_bits_int(1) != 0 self.flag_extra = self._io.read_bits_int(1) != 0 self.flag_continuation",
"= _parent self._root = _root if _root else self self._read() def _read(self): self.magic",
"3 reserved_4 = 4 reserved_5 = 5 reserved_6 = 6 reserved_7 = 7",
"= 4 atari_tos = 5 hpfs_filesystem = 6 macintosh = 7 z_system =",
"atari_tos = 5 hpfs_filesystem = 6 macintosh = 7 z_system = 8 cpm",
"self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted == True: self.encryption_header = self._io.read_bytes(12)",
"_root=None): self._io = _io self._parent = _parent self._root = _root if _root else",
"= 4 reserved_5 = 5 reserved_6 = 6 reserved_7 = 7 deflate =",
"to rebuild from pkg_resources import parse_version from modules.SIGA.kaitaistruct import __version__ as ks_version, KaitaiStruct,",
"= 8 class EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms = 2",
"self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\")",
"0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time",
"class EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms = 2 unix =",
"unknown = 255 def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent =",
"self._io.read_bytes(2) self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment",
"self._io = _io self._parent = _parent self._root = _root if _root else self",
"This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler",
"= self._io.read_bits_int(1) != 0 self.flag_continuation = self._io.read_bits_int(1) != 0 self.flag_ascii_text = self._io.read_bits_int(1) !=",
"file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources",
"_parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root",
"== True: self.extra_len = self._io.read_u2le() if self.flag_extra == True: self.extra_bytes = self._io.read_bytes(self.extra_len) if",
"packed = 2 lzhed = 3 reserved_4 = 4 reserved_5 = 5 reserved_6",
"self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size() - self._io.pos())",
"self.part_number = self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra ==",
"else self self._read() def _read(self): self.header = self._root.GzipHeader(self._io, self, self._root) self.compressed = self._io.read_bytes(((self._io.size()",
"reserved_4 = 4 reserved_5 = 5 reserved_6 = 6 reserved_7 = 7 deflate",
"!= 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1() self.operating_system = self._root.EnumOs(self._io.read_u1()) if",
"hpfs_filesystem = 6 macintosh = 7 z_system = 8 cpm = 9 tops_20",
"cpm = 9 tops_20 = 10 ntfs_filesystem = 11 qdos = 12 acorn_riscos",
"self.compression_method = self._root.EnumCompression(self._io.read_u1()) self.flag_reserved_2bits = self._io.read_bits_int(2) self.flag_encrypted = self._io.read_bits_int(1) != 0 self.flag_comment =",
"== True: self.extra_bytes = self._io.read_bytes(self.extra_len) if self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False,",
"self._io.read_bits_int(1) != 0 self.flag_comment = self._io.read_bits_int(1) != 0 self.flag_name = self._io.read_bits_int(1) != 0",
"0.7 or later is required, but you have %s\" % (ks_version)) class fm_GZip(KaitaiStruct):",
"self.flag_name == True: self.original_file_name = (self._io.read_bytes_term(0, False, True, True)).decode(u\"EUC-KR\") if self.flag_encrypted == True:",
"qdos = 12 acorn_riscos = 13 unknown = 255 def __init__(self, _io, _parent=None,",
"= self._io.read_u2le() if self.flag_extra == True: self.extra_len = self._io.read_u2le() if self.flag_extra == True:",
"deflate = 8 class EnumOs(Enum): fat_filesystem = 0 amiga = 1 vms =",
"macintosh = 7 z_system = 8 cpm = 9 tops_20 = 10 ntfs_filesystem",
"7 z_system = 8 cpm = 9 tops_20 = 10 ntfs_filesystem = 11",
"self._parent = _parent self._root = _root if _root else self self._read() def _read(self):",
"self.operating_system = self._root.EnumOs(self._io.read_u1()) if self.flag_continuation == True: self.part_number = self._io.read_u2le() if self.flag_extra ==",
"0 self.flag_ascii_text = self._io.read_bits_int(1) != 0 self._io.align_to_byte() self.modification_time = self._io.read_u4le() self.extra_flags = self._io.read_u1()"
] |
[
"class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class",
"class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[],",
"pass class CILInstructionNode: def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class",
"class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class",
"originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram: def __init__(self,Types=[],Data=[],Methods=[]): self.Types=Types self.Data=Data",
"CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode):",
"pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname",
"params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el",
"CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison):",
"CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison):",
"pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass",
"class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class",
"CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments",
"class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class",
"locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram: def __init__(self,Types=[],Data=[],Methods=[]):",
"pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass",
"CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator):",
"CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction):",
"pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass",
"class CILObject: pass class CILInstructionNode: def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\"",
"CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode):",
"CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str):",
"CILObject: pass class CILInstructionNode: def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params))",
"variable y una variable con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass",
"self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals",
"class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class",
"class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType",
"class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class",
"def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True",
"self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def",
"pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass",
"pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass",
"#Devuelve True si el tipo es correcto, se le pasa una variable y",
"class CILInstructionNode: def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode):",
"CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent",
"pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass",
"instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto, se",
"el tipo es correcto, se le pasa una variable y una variable con",
"class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class",
"self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones",
"pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass",
"es correcto, se le pasa una variable y una variable con string pass",
"class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class",
"CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[],",
"CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction):",
"pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass",
"class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class",
"pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass",
"pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def",
"class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass",
"CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction):",
"def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto,",
"class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto, se le pasa una",
"CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname",
"params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram: def",
"class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class",
"self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre,",
"def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"):",
"CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator):",
"pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass",
"pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass",
"True si el tipo es correcto, se le pasa una variable y una",
"class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class",
"CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory):",
"class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class",
"le pasa una variable y una variable con string pass class CILBinaryOperator(CILInstructionNode): pass",
"pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass",
"def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class",
"class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class",
"print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto, se le",
"CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction):",
"y una variable con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class",
"__init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos",
"pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass",
"class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class",
"def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass:",
"una variable y una variable con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator):",
"CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison):",
"pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass",
"CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic):",
"self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[],",
"class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class",
"pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass",
"CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode):",
"class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname):",
"pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator): pass",
"con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class",
"CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction):",
"CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator):",
"self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es",
"attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class",
"intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram: def __init__(self,Types=[],Data=[],Methods=[]): self.Types=Types",
"class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name,",
"CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction):",
"self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram: def __init__(self,Types=[],Data=[],Methods=[]): self.Types=Types self.Data=Data self.Methods=Methods",
"CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator):",
"class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str,",
"\"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto, se le pasa",
"class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class",
"class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class",
"CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode):",
"CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode):",
"class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class",
"CILInstructionNode: def __init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve",
"class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class",
"class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class",
"class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class",
"__init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params self.locals=locals self.intrucciones=intrucciones self.originclass=originclass self.comments=comments class CILProgram:",
"CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction):",
"valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre self.params=params",
"class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class",
"CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison):",
"class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class",
"CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass class CILAssign(CILUnaryOperator):",
"class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class",
"pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def",
"pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass",
"pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass",
"si el tipo es correcto, se le pasa una variable y una variable",
"def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos",
"self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[],",
"CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode):",
"CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction):",
"self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None):",
"pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass",
"CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction):",
"CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction):",
"pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass",
"CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class",
"pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass",
"pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name",
"pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass",
"pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass",
"pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass",
"def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre",
"pasa una variable y una variable con string pass class CILBinaryOperator(CILInstructionNode): pass class",
"CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute:",
"CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class CILStringLenght(CILStringInstruction):",
"pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass",
"__init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString",
"self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo",
"pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass",
"CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode):",
"pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass",
"correcto, se le pasa una variable y una variable con string pass class",
"pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass",
"__init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod: def __init__(self,nombre, params=[], locals=[], intrucciones=[], originclass=\"Object\",comments=\"None\"): self.nombre=nombre",
"pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass",
"class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class",
"listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class",
"class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name",
"pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass",
"class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class",
"pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass",
"__init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"): self.name=name self.attributeType=attributeType class CILClass: def",
"class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class",
"self.name=name self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration:",
"pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass",
"pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass",
"class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction): pass class",
"CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class CILIOInstruction(CILInstructionNode):",
"self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def __init__(self,nombre:str, valorString:str): self.nombre=nombre self.valorString=valorString class CILGlobalMethod:",
"pass class CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass",
"una variable con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator):",
"CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode):",
"class CILStringLenght(CILStringInstruction): pass class CILStringConcat(CILStringInstruction): pass class CILStringSubstring(CILStringInstruction): pass class CILStringEqual(CILStringInstruction): pass class",
"class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class",
"pass class CILAssign(CILUnaryOperator): pass class CILMemory(CILInstructionNode): pass class CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass",
"class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode): pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class",
"CILAllocate(CILMemory): pass class CILMethodInstruction(CILInstructionNode): pass class CILCall(CILMethodInstruction): pass class CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction):",
"CILInString(CILIOInstruction): pass class CILInInt(CILIOInstruction): pass class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod:",
"class CILAbort(CILInstructionNode): pass class CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class",
"CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class CILJump(CILInstructionNode): pass class CILUnaryOperator(CILInstructionNode):",
"pass class CILNot(CILUnaryOperator): pass class CILIntComplement(CILUnaryOperator): pass class CILComplement(CILUnaryOperator): pass class CILIsVoid(CILUnaryOperator): pass",
"__init__(self,destination=None, params=[]): self.destination=destination self.params=params def instructionPrint(self): print(str(type(self))+\" \"+str(self.destination)+\"<-\"+str(self.params)) class CILTypeCheck(CILInstructionNode): #Devuelve True si",
"tipo es correcto, se le pasa una variable y una variable con string",
"class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class",
"self.attributeType=attributeType class CILClass: def __init__(self,name,listaAtributos=[], listaMetodos=[],parent=None): self.name=name self.parent=parent self.listaAtributos=listaAtributos self.listaMetodos=listaMetodos class CILDataDeclaration: def",
"pass class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass",
"class CILEqual(CILComparison): pass class CILDifferent(CILComparison): pass class CILLabel(CILInstructionNode): pass class CILConditionalJump(CILInstructionNode): pass class",
"CILCopy(CILInstructionNode): pass class CILClassMethod: def __init__(self,localname,globalname): self.localname=localname self.globalname=globalname class CILAttribute: def __init__(self,name, attributeType=\"Object\"):",
"variable con string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass",
"CILVirtualCall(CILMethodInstruction): pass class CILArgument(CILMethodInstruction): pass class CILReturn(CILMethodInstruction): pass class CILStringInstruction(CILInstructionNode): pass class CILStringLoad(CILStringInstruction):",
"string pass class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic):",
"CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic):",
"class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class",
"class CILBinaryOperator(CILInstructionNode): pass class CILAritmetic(CILBinaryOperator): pass class CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class",
"se le pasa una variable y una variable con string pass class CILBinaryOperator(CILInstructionNode):",
"class CILIOInstruction(CILInstructionNode): pass class CILOutString(CILIOInstruction): pass class CILOutInt(CILIOInstruction): pass class CILInString(CILIOInstruction): pass class",
"class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic): pass class CILLesser(CILComparison): pass class CILLesserEqual(CILComparison): pass class",
"CILComparison(CILBinaryOperator): pass class CILPlus(CILAritmetic): pass class CILMinus(CILAritmetic): pass class CILMult(CILAritmetic): pass class CILDiv(CILAritmetic):",
"CILTypeCheck(CILInstructionNode): #Devuelve True si el tipo es correcto, se le pasa una variable"
] |
[
"exit() # Create training data files if they have not been already created",
"digits results = trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test image with",
"print \"Commands:\" print \"--g : generate new training data files\" exit() # User",
"sys.argv[0], \"filename\" print \"Enter python input.py --help for more commands\" exit() # User",
"\"--g\": print \"Creating new training data files.\" trainer.create_training_data() exit() # User enters a",
"\"--help\": print \"Usage: python input.py --command OR python input.py filename\" print \"Commands:\" print",
"files if they have not been already created if not os.path.exists(trainer.train_data_file) or not",
"one argument, if not then exit if len(sys.argv) < 2: print \"Enter file",
"train_labels = trainer.load_training_data() # Load a test image and convert it into a",
"sys if __name__ == '__main__': # Create a Trainer object contour_area_threshhold = 60",
"commands\" exit() # User enters the 'help' argument if sys.argv[1] == \"--help\": print",
"import sys if __name__ == '__main__': # Create a Trainer object contour_area_threshhold =",
"and predict the drawn digits results = trainer.knn_train(train_data, train_labels, test_data) # Show the",
"been already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training",
"Use the training data and test image to train the algorithm and predict",
"the drawn digits results = trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test",
"python\", sys.argv[0], \"filename\" print \"Enter python input.py --help for more commands\" exit() #",
"50 crop_height = 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin)",
"if they have not been already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file):",
"print \"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter python input.py --help for",
"Load training data files into Numpy arrays train_data, train_labels = trainer.load_training_data() # Load",
"import Trainer import os import sys if __name__ == '__main__': # Create a",
"new training data files\" exit() # User enters the 'generate' argument if sys.argv[1]",
"argument if sys.argv[1] == \"--g\": print \"Creating new training data files.\" trainer.create_training_data() exit()",
"the 'generate' argument if sys.argv[1] == \"--g\": print \"Creating new training data files.\"",
"== \"--g\": print \"Creating new training data files.\" trainer.create_training_data() exit() # User enters",
"User enters the 'generate' argument if sys.argv[1] == \"--g\": print \"Creating new training",
"sys.argv[1] == \"--g\": print \"Creating new training data files.\" trainer.create_training_data() exit() # User",
"not os.path.exists(input_file): print input_file, \"is not a valid file name.\" exit() # Create",
"least one argument, if not then exit if len(sys.argv) < 2: print \"Enter",
"# User enters a file name as an argument input_file = sys.argv[1] if",
"argument, if not then exit if len(sys.argv) < 2: print \"Enter file name:",
"if not os.path.exists(input_file): print input_file, \"is not a valid file name.\" exit() #",
"or not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data() # Load training",
"len(sys.argv) < 2: print \"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter python",
"algorithm and predict the drawn digits results = trainer.knn_train(train_data, train_labels, test_data) # Show",
"# User enters the 'help' argument if sys.argv[1] == \"--help\": print \"Usage: python",
"training data files into Numpy arrays train_data, train_labels = trainer.load_training_data() # Load a",
"# Create a Trainer object contour_area_threshhold = 60 crop_width = 50 crop_height =",
"Create training data files if they have not been already created if not",
"data files if they have not been already created if not os.path.exists(trainer.train_data_file) or",
"'__main__': # Create a Trainer object contour_area_threshhold = 60 crop_width = 50 crop_height",
"train_data, train_labels = trainer.load_training_data() # Load a test image and convert it into",
"the algorithm and predict the drawn digits results = trainer.knn_train(train_data, train_labels, test_data) #",
"trainer.create_test_image(input_file) # Use the training data and test image to train the algorithm",
"at least one argument, if not then exit if len(sys.argv) < 2: print",
"'help' argument if sys.argv[1] == \"--help\": print \"Usage: python input.py --command OR python",
"50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must",
"\"Usage: python input.py --command OR python input.py filename\" print \"Commands:\" print \"--g :",
"= 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter at",
"= trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test image with the results",
"arrays train_data, train_labels = trainer.load_training_data() # Load a test image and convert it",
"test_data = trainer.create_test_image(input_file) # Use the training data and test image to train",
"sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not a valid file name.\" exit()",
"\"Commands:\" print \"--g : generate new training data files\" exit() # User enters",
"Load a test image and convert it into a Numpy array test_data =",
"python input.py filename\" print \"Commands:\" print \"--g : generate new training data files\"",
"to train the algorithm and predict the drawn digits results = trainer.knn_train(train_data, train_labels,",
"--help for more commands\" exit() # User enters the 'help' argument if sys.argv[1]",
"enters the 'generate' argument if sys.argv[1] == \"--g\": print \"Creating new training data",
"enters a file name as an argument input_file = sys.argv[1] if not os.path.exists(input_file):",
"file name: python\", sys.argv[0], \"filename\" print \"Enter python input.py --help for more commands\"",
"a file name as an argument input_file = sys.argv[1] if not os.path.exists(input_file): print",
"trainer.load_training_data() # Load a test image and convert it into a Numpy array",
"60 crop_width = 50 crop_height = 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold,",
"predict the drawn digits results = trainer.knn_train(train_data, train_labels, test_data) # Show the resulting",
"then exit if len(sys.argv) < 2: print \"Enter file name: python\", sys.argv[0], \"filename\"",
"2: print \"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter python input.py --help",
"\"Creating new training data files.\" trainer.create_training_data() # Load training data files into Numpy",
"into a Numpy array test_data = trainer.create_test_image(input_file) # Use the training data and",
"a Trainer object contour_area_threshhold = 60 crop_width = 50 crop_height = 50 crop_margin",
"__name__ == '__main__': # Create a Trainer object contour_area_threshhold = 60 crop_width =",
"'generate' argument if sys.argv[1] == \"--g\": print \"Creating new training data files.\" trainer.create_training_data()",
"generate new training data files\" exit() # User enters the 'generate' argument if",
"User enters the 'help' argument if sys.argv[1] == \"--help\": print \"Usage: python input.py",
"argument if sys.argv[1] == \"--help\": print \"Usage: python input.py --command OR python input.py",
"crop_height, crop_margin) # User must enter at least one argument, if not then",
"trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test image with the results printed",
"the training data and test image to train the algorithm and predict the",
"print \"Enter python input.py --help for more commands\" exit() # User enters the",
"trainer.create_training_data() # Load training data files into Numpy arrays train_data, train_labels = trainer.load_training_data()",
"# Create training data files if they have not been already created if",
"trainer.create_training_data() exit() # User enters a file name as an argument input_file =",
"--command OR python input.py filename\" print \"Commands:\" print \"--g : generate new training",
"as an argument input_file = sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not",
"not then exit if len(sys.argv) < 2: print \"Enter file name: python\", sys.argv[0],",
"have not been already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating",
"Numpy array test_data = trainer.create_test_image(input_file) # Use the training data and test image",
"test image to train the algorithm and predict the drawn digits results =",
"object contour_area_threshhold = 60 crop_width = 50 crop_height = 50 crop_margin = 5",
"sys.argv[1] == \"--help\": print \"Usage: python input.py --command OR python input.py filename\" print",
"test image and convert it into a Numpy array test_data = trainer.create_test_image(input_file) #",
"# Load training data files into Numpy arrays train_data, train_labels = trainer.load_training_data() #",
"# User enters the 'generate' argument if sys.argv[1] == \"--g\": print \"Creating new",
"created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\"",
"if not then exit if len(sys.argv) < 2: print \"Enter file name: python\",",
"\"Creating new training data files.\" trainer.create_training_data() exit() # User enters a file name",
"enters the 'help' argument if sys.argv[1] == \"--help\": print \"Usage: python input.py --command",
"input_file = sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not a valid file",
"convert it into a Numpy array test_data = trainer.create_test_image(input_file) # Use the training",
"contour_area_threshhold = 60 crop_width = 50 crop_height = 50 crop_margin = 5 trainer",
"exit if len(sys.argv) < 2: print \"Enter file name: python\", sys.argv[0], \"filename\" print",
"name.\" exit() # Create training data files if they have not been already",
"Trainer object contour_area_threshhold = 60 crop_width = 50 crop_height = 50 crop_margin =",
"test_data) # Show the resulting test image with the results printed on top",
"and test image to train the algorithm and predict the drawn digits results",
"print \"--g : generate new training data files\" exit() # User enters the",
"\"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter python input.py --help for more",
"not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data() #",
"files.\" trainer.create_training_data() # Load training data files into Numpy arrays train_data, train_labels =",
"# Show the resulting test image with the results printed on top trainer.show_result_image(results)",
"from trainer import Trainer import os import sys if __name__ == '__main__': #",
"trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter at least one",
"crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter",
"data files\" exit() # User enters the 'generate' argument if sys.argv[1] == \"--g\":",
"name as an argument input_file = sys.argv[1] if not os.path.exists(input_file): print input_file, \"is",
"training data files.\" trainer.create_training_data() # Load training data files into Numpy arrays train_data,",
"file name.\" exit() # Create training data files if they have not been",
"array test_data = trainer.create_test_image(input_file) # Use the training data and test image to",
"# User must enter at least one argument, if not then exit if",
"train_labels, test_data) # Show the resulting test image with the results printed on",
"< 2: print \"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter python input.py",
"if __name__ == '__main__': # Create a Trainer object contour_area_threshhold = 60 crop_width",
"for more commands\" exit() # User enters the 'help' argument if sys.argv[1] ==",
"input_file, \"is not a valid file name.\" exit() # Create training data files",
"training data files if they have not been already created if not os.path.exists(trainer.train_data_file)",
"a valid file name.\" exit() # Create training data files if they have",
"crop_margin) # User must enter at least one argument, if not then exit",
"= Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter at least one argument,",
"the 'help' argument if sys.argv[1] == \"--help\": print \"Usage: python input.py --command OR",
": generate new training data files\" exit() # User enters the 'generate' argument",
"import os import sys if __name__ == '__main__': # Create a Trainer object",
"# Load a test image and convert it into a Numpy array test_data",
"name: python\", sys.argv[0], \"filename\" print \"Enter python input.py --help for more commands\" exit()",
"Numpy arrays train_data, train_labels = trainer.load_training_data() # Load a test image and convert",
"input.py --help for more commands\" exit() # User enters the 'help' argument if",
"\"--g : generate new training data files\" exit() # User enters the 'generate'",
"5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter at least",
"# Use the training data and test image to train the algorithm and",
"it into a Numpy array test_data = trainer.create_test_image(input_file) # Use the training data",
"files into Numpy arrays train_data, train_labels = trainer.load_training_data() # Load a test image",
"crop_width = 50 crop_height = 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width,",
"an argument input_file = sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not a",
"not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data() # Load training data",
"not a valid file name.\" exit() # Create training data files if they",
"os.path.exists(input_file): print input_file, \"is not a valid file name.\" exit() # Create training",
"if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data()",
"drawn digits results = trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test image",
"results = trainer.knn_train(train_data, train_labels, test_data) # Show the resulting test image with the",
"files.\" trainer.create_training_data() exit() # User enters a file name as an argument input_file",
"enter at least one argument, if not then exit if len(sys.argv) < 2:",
"\"is not a valid file name.\" exit() # Create training data files if",
"data files.\" trainer.create_training_data() exit() # User enters a file name as an argument",
"if len(sys.argv) < 2: print \"Enter file name: python\", sys.argv[0], \"filename\" print \"Enter",
"python input.py --command OR python input.py filename\" print \"Commands:\" print \"--g : generate",
"new training data files.\" trainer.create_training_data() # Load training data files into Numpy arrays",
"== \"--help\": print \"Usage: python input.py --command OR python input.py filename\" print \"Commands:\"",
"already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training data",
"print \"Usage: python input.py --command OR python input.py filename\" print \"Commands:\" print \"--g",
"User must enter at least one argument, if not then exit if len(sys.argv)",
"python input.py --help for more commands\" exit() # User enters the 'help' argument",
"a test image and convert it into a Numpy array test_data = trainer.create_test_image(input_file)",
"print \"Creating new training data files.\" trainer.create_training_data() exit() # User enters a file",
"a Numpy array test_data = trainer.create_test_image(input_file) # Use the training data and test",
"and convert it into a Numpy array test_data = trainer.create_test_image(input_file) # Use the",
"files\" exit() # User enters the 'generate' argument if sys.argv[1] == \"--g\": print",
"= trainer.load_training_data() # Load a test image and convert it into a Numpy",
"more commands\" exit() # User enters the 'help' argument if sys.argv[1] == \"--help\":",
"Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User must enter at least one argument, if",
"= trainer.create_test_image(input_file) # Use the training data and test image to train the",
"data and test image to train the algorithm and predict the drawn digits",
"crop_width, crop_height, crop_margin) # User must enter at least one argument, if not",
"input.py filename\" print \"Commands:\" print \"--g : generate new training data files\" exit()",
"into Numpy arrays train_data, train_labels = trainer.load_training_data() # Load a test image and",
"training data and test image to train the algorithm and predict the drawn",
"os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data() # Load",
"Create a Trainer object contour_area_threshhold = 60 crop_width = 50 crop_height = 50",
"OR python input.py filename\" print \"Commands:\" print \"--g : generate new training data",
"training data files\" exit() # User enters the 'generate' argument if sys.argv[1] ==",
"\"Enter python input.py --help for more commands\" exit() # User enters the 'help'",
"exit() # User enters the 'generate' argument if sys.argv[1] == \"--g\": print \"Creating",
"= 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) # User",
"file name as an argument input_file = sys.argv[1] if not os.path.exists(input_file): print input_file,",
"data files.\" trainer.create_training_data() # Load training data files into Numpy arrays train_data, train_labels",
"data files into Numpy arrays train_data, train_labels = trainer.load_training_data() # Load a test",
"trainer import Trainer import os import sys if __name__ == '__main__': # Create",
"must enter at least one argument, if not then exit if len(sys.argv) <",
"input.py --command OR python input.py filename\" print \"Commands:\" print \"--g : generate new",
"print \"Creating new training data files.\" trainer.create_training_data() # Load training data files into",
"= sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not a valid file name.\"",
"= 50 crop_height = 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height,",
"they have not been already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print",
"if sys.argv[1] == \"--g\": print \"Creating new training data files.\" trainer.create_training_data() exit() #",
"Trainer import os import sys if __name__ == '__main__': # Create a Trainer",
"image to train the algorithm and predict the drawn digits results = trainer.knn_train(train_data,",
"if sys.argv[1] == \"--help\": print \"Usage: python input.py --command OR python input.py filename\"",
"User enters a file name as an argument input_file = sys.argv[1] if not",
"filename\" print \"Commands:\" print \"--g : generate new training data files\" exit() #",
"training data files.\" trainer.create_training_data() exit() # User enters a file name as an",
"os import sys if __name__ == '__main__': # Create a Trainer object contour_area_threshhold",
"exit() # User enters the 'help' argument if sys.argv[1] == \"--help\": print \"Usage:",
"== '__main__': # Create a Trainer object contour_area_threshhold = 60 crop_width = 50",
"exit() # User enters a file name as an argument input_file = sys.argv[1]",
"\"filename\" print \"Enter python input.py --help for more commands\" exit() # User enters",
"print input_file, \"is not a valid file name.\" exit() # Create training data",
"new training data files.\" trainer.create_training_data() exit() # User enters a file name as",
"crop_height = 50 crop_margin = 5 trainer = Trainer(contour_area_threshhold, crop_width, crop_height, crop_margin) #",
"image and convert it into a Numpy array test_data = trainer.create_test_image(input_file) # Use",
"not been already created if not os.path.exists(trainer.train_data_file) or not os.path.exists(trainer.train_labels_file): print \"Creating new",
"valid file name.\" exit() # Create training data files if they have not",
"train the algorithm and predict the drawn digits results = trainer.knn_train(train_data, train_labels, test_data)",
"= 60 crop_width = 50 crop_height = 50 crop_margin = 5 trainer =",
"argument input_file = sys.argv[1] if not os.path.exists(input_file): print input_file, \"is not a valid",
"os.path.exists(trainer.train_labels_file): print \"Creating new training data files.\" trainer.create_training_data() # Load training data files"
] |
[
"met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC",
"test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result, dict, \"Dictionary",
"SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result =",
"import ioc_scanner as iocs from os import path class IOCSTest(TestCase): \"\"\" IOC Processor",
"import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file =",
"ioc_scanner as iocs from os import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests",
"TestCase, main import ioc_scanner as iocs from os import path class IOCSTest(TestCase): \"\"\"",
"= 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self):",
"'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'),",
"\"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file)",
"utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script",
"empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\")",
"\"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result",
"def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is",
"compares them to known IOCs. # Unit Testing for IOC Scanner. # Import",
"import TestCase, main import ioc_scanner as iocs from os import path class IOCSTest(TestCase):",
"REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file",
"IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC",
"Description: Script to get IP Addresses from Files, and compares them to known",
"#!/usr/bin/venv python3 # -*- coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz #",
"test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\")",
"empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\")",
"\"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default",
"IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file,",
"self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt'",
"is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file",
"self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'),",
"# ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script to get",
"BlackSquirrelz # Date: 2021-03-10 # Description: Script to get IP Addresses from Files,",
"self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is",
"default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\")",
"empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result,",
"Date: 2021-03-10 # Description: Script to get IP Addresses from Files, and compares",
"from os import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self):",
"test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result, dict, \"Dictionary requirement",
"Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict,",
"for IOC Scanner. # Import Statements from unittest import TestCase, main import ioc_scanner",
"IOCs. # Unit Testing for IOC Scanner. # Import Statements from unittest import",
"# Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script to get IP Addresses",
"os import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file",
"# Import Statements from unittest import TestCase, main import ioc_scanner as iocs from",
"def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result, dict,",
"-*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script to",
"Script to get IP Addresses from Files, and compares them to known IOCs.",
"is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file)",
"# Description: Script to get IP Addresses from Files, and compares them to",
"IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result,",
"ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script to get IP",
"IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log'",
"def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not",
"Testing for IOC Scanner. # Import Statements from unittest import TestCase, main import",
"iocs from os import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def",
"IP Addresses from Files, and compares them to known IOCs. # Unit Testing",
"# -*- coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10",
"Statements from unittest import TestCase, main import ioc_scanner as iocs from os import",
"requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default",
"Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary",
"-*- coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 #",
"test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def",
"self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def",
"iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC",
"from unittest import TestCase, main import ioc_scanner as iocs from os import path",
"='test_directory/test_2/ABC.log' default_regex_file = 'iocs/ioc_regex.txt' result = iocs.generic_regex(default_regex_file, test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not",
"path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log'",
"result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default",
"known IOCs. # Unit Testing for IOC Scanner. # Import Statements from unittest",
"empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self): test_file ='test_directory/test_2/ABC.log' default_regex_file =",
"from Files, and compares them to known IOCs. # Unit Testing for IOC",
"coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date: 2021-03-10 # Description:",
"2021-03-10 # Description: Script to get IP Addresses from Files, and compares them",
"and compares them to known IOCs. # Unit Testing for IOC Scanner. #",
"IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC",
"<reponame>BlackSquirrelz/ioc_detektor #!/usr/bin/venv python3 # -*- coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz",
"\"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result = iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement",
"Import Statements from unittest import TestCase, main import ioc_scanner as iocs from os",
"is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is",
"not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP",
"unittest import TestCase, main import ioc_scanner as iocs from os import path class",
"dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\")",
"Author: BlackSquirrelz # Date: 2021-03-10 # Description: Script to get IP Addresses from",
"\"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is empty.\") def test_generic_regex_function(self):",
"Scanner. # Import Statements from unittest import TestCase, main import ioc_scanner as iocs",
"Addresses from Files, and compares them to known IOCs. # Unit Testing for",
"\"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default",
"# Unit Testing for IOC Scanner. # Import Statements from unittest import TestCase,",
"Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX",
"as iocs from os import path class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\"",
"to get IP Addresses from Files, and compares them to known IOCs. #",
"# Date: 2021-03-10 # Description: Script to get IP Addresses from Files, and",
"test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\")",
"IOC Scanner. # Import Statements from unittest import TestCase, main import ioc_scanner as",
"python3 # -*- coding: utf-8 -*- # ioc_scanner_test.py # Author: BlackSquirrelz # Date:",
"IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS",
"get IP Addresses from Files, and compares them to known IOCs. # Unit",
"main import ioc_scanner as iocs from os import path class IOCSTest(TestCase): \"\"\" IOC",
"Files, and compares them to known IOCs. # Unit Testing for IOC Scanner.",
"= iocs.get_ip(test_file) self.assertIsInstance(result, dict, \"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash",
"is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'), \"Default REGEX IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_shells.txt'), \"Default SHELLS IOC is",
"class IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result",
"Unit Testing for IOC Scanner. # Import Statements from unittest import TestCase, main",
"IOCSTest(TestCase): \"\"\" IOC Processor Tests \"\"\" def test_get_ip_function(self): test_file = 'test_directory/test_2/ABC.log' result =",
"to known IOCs. # Unit Testing for IOC Scanner. # Import Statements from",
"\"Dictionary requirement not met.\") def test_default_ioc_directory(self): self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'),",
"self.assertTrue(path.exists('iocs/ioc_hashes.txt'), \"Default Hash IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_ip.txt'), \"Default IP IOC is empty.\") self.assertTrue(path.exists('iocs/ioc_regex.txt'),",
"them to known IOCs. # Unit Testing for IOC Scanner. # Import Statements"
] |
[
"'{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims, value):",
"details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name,",
"} } elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL,",
"OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url,",
"'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL",
"= self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self,",
"def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return",
"parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1:",
"= '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options",
"= { 'iss': { 'essential': True, 'validate': validate_iss, } } else: raise ValueError('Invalid",
"class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version",
"ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = {",
"OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version ==",
"token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def",
"tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options",
"Loginpass Backend of Azure AD. :copyright: (c) 2018 by <NAME> :license: BSD, see",
"= 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = { 'iss': { 'essential': True,",
"import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if",
"= { 'iss': { 'values': [issuer_url] } } elif version == 2: authorize_url",
"claims_options is None: claims_options = { 'iss': { 'values': [issuer_url] } } elif",
"Azure AD. :copyright: (c) 2018 by <NAME> :license: BSD, see LICENSE for more",
"= '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = {",
"tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return",
"BSD, see LICENSE for more details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token",
"def create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant)",
"elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url",
"profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant)",
"version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url =",
"resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'),",
"= '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token,",
"return self.parse_openid(**kwargs) if version == 2: return AzureADv2 else: return AzureAD Azure =",
"profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json())",
"value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = { 'iss': {",
"nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL =",
"**kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def",
"if claims_options is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss ==",
"token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant)",
"loginpass.azure ~~~~~~~~~~~~~~~ Loginpass Backend of Azure AD. :copyright: (c) 2018 by <NAME> :license:",
"'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL,",
"1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if",
"profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2: return AzureADv2 else: return AzureAD",
"UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version",
"= { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'},",
"tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status()",
"'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = { 'iss': { 'values': [issuer_url] }",
"OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs':",
"'{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs)",
"def profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2: return AzureADv2 else: return",
"authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self,",
"tenant, version=1, claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url =",
"= '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url':",
"'{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None):",
"claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs):",
"tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims, value): iss",
"for more details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/'",
"[issuer_url] } } elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url =",
"self.parse_openid(**kwargs) if version == 2: return AzureADv2 else: return AzureAD Azure = create_azure_backend('azure',",
"= '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url,",
"} else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name",
"AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url':",
"**kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options,",
"is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options",
"version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url':",
"\"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant,",
"tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None:",
"validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = { 'iss':",
"iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = { 'iss': { 'essential':",
"token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self,",
"{ 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, }",
"claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant)",
"'validate': validate_iss, } } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc'",
"{ 'iss': { 'values': [issuer_url] } } elif version == 2: authorize_url =",
"AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version ==",
"'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def",
"{ 'values': [issuer_url] } } elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant)",
"JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2:",
":license: BSD, see LICENSE for more details. \"\"\" from ._core import UserInfo, OAuthBackend,",
"self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def",
"True, 'validate': validate_iss, } } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE =",
"'2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url,",
"'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs):",
"email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL,",
"'iss': { 'values': [issuer_url] } } elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL,",
"authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options",
"nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs)",
"JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp =",
"token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL",
"by <NAME> :license: BSD, see LICENSE for more details. \"\"\" from ._core import",
"def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class",
"_BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1: authorize_url",
"None: claims_options = { 'iss': { 'values': [issuer_url] } } elif version ==",
"token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return",
"UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce )",
":copyright: (c) 2018 by <NAME> :license: BSD, see LICENSE for more details. \"\"\"",
"of Azure AD. :copyright: (c) 2018 by <NAME> :license: BSD, see LICENSE for",
"'iss': { 'essential': True, 'validate': validate_iss, } } else: raise ValueError('Invalid version') class",
"class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com',",
"None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options =",
"= '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid'])",
"create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url",
"2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant)",
"'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = { 'iss': { 'essential': True, 'validate':",
"return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce",
"value claims_options = { 'iss': { 'essential': True, 'validate': validate_iss, } } else:",
"} JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp",
"= name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope':",
"= '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is",
"2018 by <NAME> :license: BSD, see LICENSE for more details. \"\"\" from ._core",
"is None: claims_options = { 'iss': { 'values': [issuer_url] } } elif version",
"Backend of Azure AD. :copyright: (c) 2018 by <NAME> :license: BSD, see LICENSE",
"if claims_options is None: claims_options = { 'iss': { 'values': [issuer_url] } }",
"'{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is",
"'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL =",
"{'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url",
"._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None):",
"return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL,",
"version=1, claims_options=None): if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL,",
"= '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims,",
"'{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2: return AzureADv2",
"issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims, value): iss =",
"authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL, tenant) if",
"AD. :copyright: (c) 2018 by <NAME> :license: BSD, see LICENSE for more details.",
"'essential': True, 'validate': validate_iss, } } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE",
"<filename>loginpass/azure.py<gh_stars>0 \"\"\" loginpass.azure ~~~~~~~~~~~~~~~ Loginpass Backend of Azure AD. :copyright: (c) 2018 by",
"'{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = { 'iss':",
"'values': [issuer_url] } } elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url",
"def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value claims_options = {",
"validate_iss, } } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME",
"name OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid",
"OAUTH_CONFIG = { 'api_base_url': 'graph.microsoft.com', 'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email",
"= 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1, claims_options=None): if version == 1: authorize_url =",
"== 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url = '{}{}/v2.0'.format(_BASE_URL,",
"~~~~~~~~~~~~~~~ Loginpass Backend of Azure AD. :copyright: (c) 2018 by <NAME> :license: BSD,",
"more details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def",
"if version == 2: return AzureADv2 else: return AzureAD Azure = create_azure_backend('azure', 'common')",
"} elif version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant)",
"issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = { 'iss': { 'values':",
"version == 2: authorize_url = '{}{}/oauth2/v2.0/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/v2.0/token'.format(_BASE_URL, tenant) issuer_url =",
"claims_options = { 'iss': { 'essential': True, 'validate': validate_iss, } } else: raise",
"{ 'iss': { 'essential': True, 'validate': validate_iss, } } else: raise ValueError('Invalid version')",
"parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant)",
"'access_token_url': token_url, 'authorize_url': authorize_url, 'client_kwargs': {'scope': 'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL,",
"== 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant)",
"resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token(",
"LICENSE for more details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL =",
"from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL = 'https://login.microsoftonline.com/' def create_azure_backend(name, tenant, version=1,",
"= '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2: return",
"url = '{}{}/openid/userinfo'.format(_BASE_URL, tenant) resp = self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self,",
"**kwargs): return self.parse_openid(**kwargs) if version == 2: return AzureADv2 else: return AzureAD Azure",
"claims_options = { 'iss': { 'values': [issuer_url] } } elif version == 2:",
"claims_options is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss == value",
"(c) 2018 by <NAME> :license: BSD, see LICENSE for more details. \"\"\" from",
"\"\"\" loginpass.azure ~~~~~~~~~~~~~~~ Loginpass Backend of Azure AD. :copyright: (c) 2018 by <NAME>",
"'openid email profile'}, } JWK_SET_URL = '{}{}/discovery/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): url =",
"see LICENSE for more details. \"\"\" from ._core import UserInfo, OAuthBackend, parse_id_token _BASE_URL",
"<NAME> :license: BSD, see LICENSE for more details. \"\"\" from ._core import UserInfo,",
"parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'], claims_options, token.get('access_token'), nonce ) class AzureADv2(AzureAD):",
"if version == 1: authorize_url = '{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url",
"raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG =",
") class AzureADv2(AzureAD): JWK_SET_URL = '{}{}/discovery/v2.0/keys'.format(_BASE_URL, tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if",
"'{}{}/v2.0'.format(_BASE_URL, tenant) if claims_options is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return",
"iss == value claims_options = { 'iss': { 'essential': True, 'validate': validate_iss, }",
"return iss == value claims_options = { 'iss': { 'essential': True, 'validate': validate_iss,",
"== value claims_options = { 'iss': { 'essential': True, 'validate': validate_iss, } }",
"tenant) if claims_options is None: def validate_iss(claims, value): iss = 'https://login.microsoftonline.com/{}/v2.0'.format(claims['tid']) return iss",
"} } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME =",
"tenant) def profile(self, **kwargs): return self.parse_openid(**kwargs) if version == 2: return AzureADv2 else:",
"'{}{}/oauth2/authorize'.format(_BASE_URL, tenant) token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None:",
"tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = { 'iss': {",
"{ 'essential': True, 'validate': validate_iss, } } else: raise ValueError('Invalid version') class AzureAD(OAuthBackend):",
"else: raise ValueError('Invalid version') class AzureAD(OAuthBackend): OAUTH_TYPE = '2.0,oidc' OAUTH_NAME = name OAUTH_CONFIG",
"self.get(url, **kwargs) resp.raise_for_status() return UserInfo(**resp.json()) def parse_openid(self, token, nonce=None): return parse_id_token( self, token['id_token'],",
"token_url = '{}{}/oauth2/token'.format(_BASE_URL, tenant) issuer_url = 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options =",
"= 'https://sts.windows.net/{}/'.format(tenant) if claims_options is None: claims_options = { 'iss': { 'values': [issuer_url]"
] |
[
"pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\",",
"= c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures =",
"fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et",
"import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main",
"[c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0,",
"text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ]",
"100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1)",
"lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths",
"elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] }",
"plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\")",
"cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\")",
"font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\",",
"(m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s))",
"1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of Sound (\\si{\\meter\\per\\second})\") plt.ylabel(r\"Depth (\\si{\\meter})\") plt.savefig(Path(\"final_output/figures/ideal.pdf\"))",
"= c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype =",
"0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35))",
"depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0)",
"fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\",",
"lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures",
"1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig, plots =",
"np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0)",
"} matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt # import netCDF4 try: lib",
"plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10,",
"0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000,",
"cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double",
"ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s",
"cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title)",
"c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double)",
"= np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al,",
"'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp",
"plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\",",
"lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype",
"al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed",
"np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2, 'col',",
"netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes",
"Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure()",
"\"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot",
"= c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100,",
"plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t,",
"(m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d,",
"t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature",
"fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al.",
"r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt # import",
"pyplot as plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as",
"Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of Sound",
"lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes",
"\"pdflatex\", \"font.family\": \"serif\", # use serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\":",
"(\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s))",
"numpy as np import seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex",
"= { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font for text elements",
"ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid()",
"r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt",
"lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype",
"OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes",
"plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top':",
"np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3,",
"rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp =",
"Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3),",
"matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt # import netCDF4 try: lib =",
"matplotlib import pyplot as plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except",
"as np import seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex =",
"= np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco =",
"ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d",
"ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel,",
"True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps,",
"'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d",
"t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1])",
"pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40,",
"fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO",
"(Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths,",
"= [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths =",
"<gh_stars>0 #!/usr/bin/env python3 from ctypes import cdll, c_double, CFUNCTYPE import numpy as np",
"0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import",
"lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes",
"d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False)",
"= np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100,",
"plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy,",
"s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps,",
"\"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font for text elements \"text.usetex\": True,",
"title, filename): fig, plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3,",
"fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths)",
"ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title,",
"10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s =",
"plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid()",
"np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1)",
"cdll, c_double, CFUNCTYPE import numpy as np import seaborn from pathlib import Path",
"plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp =",
"35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d =",
"0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s,",
"plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths)",
"salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\")",
"r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt # import netCDF4",
"[c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double)",
"] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt # import netCDF4 try:",
"40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1)",
"dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal =",
"np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth,",
"s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename)",
"= np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2,",
"Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use",
"lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40,",
"try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes =",
"plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation",
"plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib",
"as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes =",
"import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\")",
"np import seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = {",
"and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160,",
"#!/usr/bin/env python3 from ctypes import cdll, c_double, CFUNCTYPE import numpy as np import",
"[c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double]",
"= np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename):",
"= plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\")",
"depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities",
"from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\":",
"3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def",
"0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d,",
"2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of",
"import numpy as np import seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\")",
"= plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature",
"c_double, CFUNCTYPE import numpy as np import seaborn from pathlib import Path import",
"import pyplot as plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError",
"lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double]",
"plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of Sound (\\si{\\meter\\per\\second})\") plt.ylabel(r\"Depth",
"c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double",
"t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\",",
"plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\"))",
"plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities)",
"\"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\"))",
"python3 from ctypes import cdll, c_double, CFUNCTYPE import numpy as np import seaborn",
"2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t,",
"\"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000,",
"lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps",
"d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\")",
"ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2,",
"(ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\")",
"= np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000,",
"[ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as",
"'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t,",
"plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s,",
"plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy",
"np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity",
"1) def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2, 'col', 'row', True,",
"figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp,",
"np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double)",
"plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d,",
"lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype",
"rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities, depths) cp",
"'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp = plots[0][0].contour(t, d, ufunc(d,t,",
"import seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\":",
"\"font.family\": \"serif\", # use serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5,",
"dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy",
"= np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5,",
"= plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid()",
"0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths) cp =",
"40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3,",
"use serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\",",
"= np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities =",
"s, d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp,",
"np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig,",
"for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\"",
"plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp,",
"1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45,",
"pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font for text",
"except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double",
"matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font",
"3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc, title, filename): fig, plots",
"fig, plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08,",
"(\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen",
"= plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92},",
"d = np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\",",
"[c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double]",
"ctypes import cdll, c_double, CFUNCTYPE import numpy as np import seaborn from pathlib",
"{ \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font for text elements \"text.usetex\":",
"# import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib =",
"100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal",
"serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\",",
"et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0)",
"(ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and Millero",
"def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={",
"Millero 1995)\", Path(\"final_output/figures/unesco.pdf\")) plot_contours(ufunc_leroy, \"Leroy et al. 2008\", Path(\"final_output/figures/leroy.pdf\")) plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3,",
"plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco, \"UNESCO Equation (Chen and",
"plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s, d = np.meshgrid(salinities,",
"cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth",
"salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco = np.frompyfunc(lib.unesco_depth, 3, 1) ufunc_leroy =",
"r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib import pyplot as plt #",
"\"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from matplotlib",
"= c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype =",
"5, 1) def plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2, 'col', 'row',",
"plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") plots[1][0].set_ylabel(\"Salinity (ppt)\") fig.suptitle(title) plots[0][0].grid() plots[0][1].grid() plots[1][0].grid() fig.delaxes(plots[1][1]) fig.savefig(filename) plot_contours(ufunc_unesco,",
"1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of Sound (\\si{\\meter\\per\\second})\") plt.ylabel(r\"Depth (\\si{\\meter})\")",
"= np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False)",
"np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps = np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0,",
"= [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double lib.ideal_sound_channel.argtypes =",
"depths) cp = plots[0][0].contour(t, d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth",
"from ctypes import cdll, c_double, CFUNCTYPE import numpy as np import seaborn from",
"= [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double) temps =",
"'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d =",
"cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype =",
"seaborn from pathlib import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\",",
"filename): fig, plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom':",
"d, ufunc(d,t, 35)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][0].set_ylim(2000, 0) plots[0][0].set_ylabel(\"Depth (m)\") plots[0][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\") s,",
"CFUNCTYPE import numpy as np import seaborn from pathlib import Path import matplotlib",
"as plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e:",
"= cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype =",
"# use serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [",
"import cdll, c_double, CFUNCTYPE import numpy as np import seaborn from pathlib import",
"plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity",
"c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes = [c_double,c_double,c_double] lib.leroy_et_al.restype = c_double",
"\"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex)",
"c_double lib.ideal_sound_channel.argtypes = [c_double,c_double,c_double,c_double,c_double] lib.ideal_sound_channel.restype = c_double depths = np.linspace(0,2000,5000,dtype=np.double) pressures = np.linspace(0,1000,5000,dtype=np.double)",
"temps = np.linspace(0, 40, 100, dtype=np.double) salinities = np.linspace(0, 40, 100, dtype=np.double) ufunc_unesco",
"fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000, 0) plots[0][1].set_ylabel(\"Depth (m)\") plots[0][1].set_xlabel(\"Salinity (ppt)\") t,s = np.meshgrid(temps, salinities) cp",
"= [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double] lib.unesco_pressure.restype = c_double lib.leroy_et_al.argtypes =",
"True, \"errorbar.capsize\": 0.5, \"pgf.preamble\": [ r\"\\usepackage[utf8]{inputenc}\", r\"\\usepackage[T1]{fontenc}\", r\"\\usepackage{mathpazo}\", r\"\\usepackage[version-1-compatibility]{siunitx}\" ] } matplotlib.rcParams.update(pgf_with_pdflatex) from",
"plot_contours(ufunc, title, filename): fig, plots = plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace':",
"e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype = c_double lib.unesco_pressure.argtypes = [c_double,c_double,c_double]",
"\"serif\", # use serif/main font for text elements \"text.usetex\": True, \"errorbar.capsize\": 0.5, \"pgf.preamble\":",
"import Path import matplotlib matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", #",
"matplotlib.use(\"pgf\") pgf_with_pdflatex = { \"pgf.texsystem\": \"pdflatex\", \"font.family\": \"serif\", # use serif/main font for",
"1) ufunc_leroy = np.frompyfunc(lib.leroy_et_al, 3, 1) ufunc_ideal = np.frompyfunc(lib.ideal_sound_channel, 5, 1) def plot_contours(ufunc,",
"gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5)) t, d = np.meshgrid(temps, depths)",
"plt.subplots(2, 2, 'col', 'row', True, gridspec_kw={ 'hspace': 0.3, 'bottom': 0.08, 'top': 0.92}, figsize=(5,5))",
"from matplotlib import pyplot as plt # import netCDF4 try: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\")",
"np.meshgrid(salinities, depths) cp = plots[0][1].contour(s, d, ufunc(d, 10, s)) plt.clabel(cp, fmt=\"%d\", rightside_up=False) plots[0][1].set_ylim(2000,",
"= cdll.LoadLibrary(\"pythonfile/libProjectPython.dylib\") except OSError as e: lib = cdll.LoadLibrary(\"pythonfile/libProjectPython.so\") lib.unesco_depth.argtypes = [c_double,c_double,c_double] lib.unesco_depth.restype",
"plt.figure() plt.plot(1000*ufunc_ideal(depths, 1160, 1.3, 1.45, 1.14e-3), depths) plt.ylim(2000, 0) plt.xlabel(r\"Speed of Sound (\\si{\\meter\\per\\second})\")",
"= np.meshgrid(temps, salinities) cp = plots[1][0].contour(t,s, ufunc(1000, t, s)) plt.clabel(cp, fmt=\"%d\") plots[1][0].set_xlabel(r\"Temperature (\\si{\\degreeCelsius})\")"
] |
[
"8) rev_chars = \\ ((chr(i) if i != 0xff else Xor.zero) for i",
"= [] for k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c",
"only (Requires %esi = -0x34, %dl = 0x30 ^ 0xff = 0xcf and",
"\"\", \"\", \"\", \"\", \"\" word_size = 2 dword_size = 4 qword_size =",
"\\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print",
"src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\"",
"Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp,",
"\\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\")",
"self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\")",
"bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod def",
"aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\")",
"(-len(sc) % 4) * \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc + \"",
"%esi)\") return sc += (-len(sc) % 4) * \"G\" # \"G\" -> \"inc",
"valid chars import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One",
"self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx =",
"is_validff = is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i ==",
"from operator import xor; \\ # of = lambda *args: reduce(xor, args, 0)",
"hundreds = 0 # 4 = Assembly()(\"inc %esp; pop %ecx; push %ecx; dec",
"\"__main__\": if Utils.verbose: Xor.display() from sys import argv if len(argv) < 2 or",
"[z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z in",
"valid bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in",
"def display(): for i in range(len(Xor.splits)): print hex(i) + \" = \" +",
"hex(i) + \" = \" + \\ \" ^ \".join(hex(x) for x in",
"in splits): splits[x ^ z] = [x, z] for x in valid_bytesff: for",
"n >= 0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro()",
"splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z in valid_bytes:",
"def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\")",
"self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx,",
"len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if",
"valid_chars] # List of validff bytes (byte 0xff added for xor completude) valid_bytesff",
"y and z are valid bytes and that 2 * (x * 0x100",
"\\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg =",
"of a validff byte and valid bytes splits = {} splits[0xff] = [0xff,",
"assert(len(bytes) <= arch / 8) rev_chars = \\ ((chr(i) if i != 0xff",
"import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char",
"x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i +=",
"words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i",
"\"inc %edi\" Utils.debug(sc + \" : \" + str(len(sc)) + \" bytes.\") all_words",
"not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi,",
"= self.len - 1 if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble()",
"* \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc + \" : \" +",
"0) # String of valid chars import string;\\ valid_chars = \\ (string.digits +",
"Converts a series of bytes into its integer representation, but replacing the byte",
"i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax, ecx, edx,",
"hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\")",
"i += 1 while (i < words_nb): x1, x2 = Xor.dups[words[i - 1][-1]]",
"range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c in sc[4 * k:4 *",
"z in valid_bytes: if not (x ^ z in splits): splits[x ^ z]",
"(\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word =",
"self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\"",
"set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\")",
"\"%edx\", edx = \"%eax\", \\ esi = \"%eax\", edi = \"%eax\", \\ ebp",
"array Output = words : (byte array) array, verifying that for j in",
"self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax",
"for i in range(len(Xor.splits)): print hex(i) + \" = \" + \\ \"",
"ebx = \"%edx\", \\ ecx = \"%edx\", edx = \"%eax\", \\ esi =",
"Xor.valid_bytes: for twice in Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100 +",
"+= 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series",
": \" + str(len(sc)) + \" bytes.\") all_words = [] for k in",
"/ 4): all_words.append( \\ Xor.split([ord(c) for c in sc[4 * k:4 * (k",
"__init__(self, sc, arch): self.autoassemble = False if arch == 64: self.eax, self.ecx, self.edx,",
"self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display()",
"x, y, z verifying that y and z are valid bytes and that",
"words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue",
"%esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\")",
"else Xor.zero) for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in",
"x in word) words = [[] for i in range(words_nb)] for byte in",
"+ \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor",
"\"\"\" xor operator with arbitrary arity \"\"\" acc = 0 for arg in",
"= [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z",
"- 1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words",
"self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for",
"\"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\")",
"self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\",",
"self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx,",
"\"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code",
"in range(len(Xor.splits)): print hex(i) + \" = \" + \\ \" ^ \".join(hex(x)",
"code_offset = self.len - 1 if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset))",
"str(len(sc)) + \" bytes.\") all_words = [] for k in range(len(sc) / 4):",
"+ twice) + once: return once, twice, hundreds offset += 1 assert(False) @staticmethod",
"= \"%edx\", \\ ecx = \"%edx\", edx = \"%eax\", \\ esi = \"%eax\",",
"i != 0xff else Xor.zero) for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\")",
"% 4) * \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc + \" :",
"2 * (x * 0x100 + y) + z = offset + x",
"\"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" + argv[0] + \\ \"'",
"^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word",
"[x, y, z] @staticmethod def display(): for i in range(len(Xor.splits)): print hex(i) +",
"self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset = self.len - 1 if",
"the byte 0xff by a valid one \"\"\" assert(len(bytes) <= arch / 8)",
"= \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs()",
"z] @staticmethod def display(): for i in range(len(Xor.splits)): print hex(i) + \" =",
"valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes",
"y in valid_bytes: for z in valid_bytes: if not (x ^ y ^",
"x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word : byte array",
"Utils.debug(sc + \" : \" + str(len(sc)) + \" bytes.\") all_words = []",
"\\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue()",
"\"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc)",
"1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class",
"Xor.zero) for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars)",
"with arbitrary arity \"\"\" acc = 0 for arg in args: acc ^=",
"\"x\" else \"\" \\ for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv)",
"self(\"inc\" if n >= 0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\")",
"in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in",
"once: return once, twice, hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch",
"return acc # from functools import reduce; from operator import xor; \\ #",
"in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying",
"List of validff bytes (byte 0xff added for xor completude) valid_bytesff = [ord(c)",
"def split(word): \"\"\" Input = word : byte array Output = words :",
"but replacing the byte 0xff by a valid one \"\"\" assert(len(bytes) <= arch",
"self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\",",
"ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi)",
"k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c in sc[4 *",
"def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\")",
"ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that",
"\"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod def of(*args): \"\"\"",
"a valid one \"\"\" assert(len(bytes) <= arch / 8) rev_chars = \\ ((chr(i)",
"== 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\",
"i in word) if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff,",
"%esi = -0x34, %dl = 0x30 ^ 0xff = 0xcf and %ecx =",
"[x, z] for x in valid_bytesff: for y in valid_bytes: for z in",
"and valid bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z",
"in range(abs(n)): self(\"inc\" if n >= 0 else \"dec\", reg) @self.macro() def pop_eip(reg):",
"{} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] = [z]",
"print \"'\" + argv[0] + \\ \"' error: 64 bits support not implemented",
"1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words)",
"<filename>helpers/alphanumeric.py<gh_stars>10-100 from assembly import Assembly # String of forbidden chars forbidden_chars = \"\"",
"incpoppushdec for once in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset == \\",
"z in splits): splits[x ^ y ^ z] = [x, y, z] @staticmethod",
"z in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x",
"= [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z in valid_bytes: if",
"+ z = offset + x + (x ? 4 : 0) \"\"\"",
"in args: acc ^= arg return acc # from functools import reduce; from",
"bytes split as tuples of a validff byte and valid bytes splits =",
"for byte in word: i = 0 for x in Xor.splits[byte]: words[i].append(x) i",
"\"%edx\", \\ ecx = \"%edx\", edx = \"%eax\", \\ esi = \"%eax\", edi",
"self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\",",
"is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for",
"self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i in range(abs(n)):",
"64 bits support not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\",
"self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\",",
"range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" +",
"range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for",
"Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if",
"= \"\" class Utils: verbose = False # Is debug printing activated? @staticmethod",
"once in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset == \\ 2*(hundreds *",
"in range(0x100): if hundreds == 1: offset += incpoppushdec for once in Xor.valid_bytes:",
"# One valid char will represent 0xff zero = valid_chars[0] # List of",
"rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if n >= 0 else \"dec\",",
"self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes",
"== self.dword_size) is_validff = True for i in word: is_validff = is_validff and",
"= \" + \\ \" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def",
"if arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi",
"+ argv[0] + \\ \"' error: 64 bits support not implemented yet\" exit(1)",
"= \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\",",
"!= 0xff else Xor.zero) for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for",
"2*(hundreds * 0x100 + twice) + once: return once, twice, hundreds offset +=",
"\"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"):",
"opcodes only (Requires %esi = -0x34, %dl = 0x30 ^ 0xff = 0xcf",
"in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i)",
"incpoppushdec = 4 for hundreds in range(0x100): if hundreds == 1: offset +=",
"byte in word: i = 0 for x in Xor.splits[byte]: words[i].append(x) i +=",
"valid_bytes: if not (x ^ y ^ z in splits): splits[x ^ y",
"(x ^ y in valid_bytes): dups[x ^ y] = [x, y] # Dictionary",
"(x ? 4 : 0) \"\"\" hundreds = 0 # 4 = Assembly()(\"inc",
"j in range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got",
"self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i in",
"from sys import argv if len(argv) < 2 or len(argv) > 3: print",
"from assembly import Assembly # String of forbidden chars forbidden_chars = \"\" class",
"in range(words_nb)] for byte in word: i = 0 for x in Xor.splits[byte]:",
"!= \"x\" else \"\" \\ for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if",
"if len(argv) == 3 else 32 code = Alphanumeric(sc, arch) if Utils.verbose: print",
"\\ \"0x\" + str(34 + i) + \"(%esp, %esi)\") return sc += (-len(sc)",
"self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\",",
"* 0x100 + y) + z = offset + x + (x ?",
"aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\")",
"\"%eax\", \\ esi = \"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\" )",
"0xff by a valid one \"\"\" assert(len(bytes) <= arch / 8) rev_chars =",
"activated? @staticmethod def none(*args): return None @staticmethod def debug(*ss): if Utils.verbose: for s",
"^ z in splits): splits[x ^ z] = [x, z] for x in",
"hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble =",
"Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in word) words = [[] for",
"ebx, esp, ebp, esi, edi = \"\", \"\", \"\", \"\", \"\", \"\", \"\",",
"valid_bytes): dups[x ^ y] = [x, y] # Dictionary of: bytes split as",
"ebp, esi, edi = \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size",
"rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor operator with arbitrary arity \"\"\"",
"\"\"\" Converts a series of bytes into its integer representation, but replacing the",
"arch / 8) rev_chars = \\ ((chr(i) if i != 0xff else Xor.zero)",
"Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" +",
"+ once: return once, twice, hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes,",
"aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg",
"@self.macro() def rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if n >= 0",
"y ^ z] = [x, y, z] @staticmethod def display(): for i in",
"word: i = 0 for x in Xor.splits[byte]: words[i].append(x) i += 1 while",
"words[i - 1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return",
"return None @staticmethod def debug(*ss): if Utils.verbose: for s in ss: print s",
"bytes.\") all_words = [] for k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c)",
"def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" +",
"Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \" + str(code.len)",
"in Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100 + twice) + once:",
"acc = 0 for arg in args: acc ^= arg return acc #",
"series of bytes into its integer representation, but replacing the byte 0xff by",
"\"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size = 2 dword_size = 4",
"__name__ == \"__main__\": if Utils.verbose: Xor.display() from sys import argv if len(argv) <",
"acc # from functools import reduce; from operator import xor; \\ # of",
"twice in Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100 + twice) +",
"4 : 0) \"\"\" hundreds = 0 # 4 = Assembly()(\"inc %esp; pop",
"self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg):",
"for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3 else 32",
"arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \"",
"\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size = 2 dword_size =",
"= Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii print",
"str(34 + i) + \"(%esp, %esi)\") return sc += (-len(sc) % 4) *",
"\"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\ ecx =",
"self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\")",
"bytes and that 2 * (x * 0x100 + y) + z =",
"= [x, y, z] @staticmethod def display(): for i in range(len(Xor.splits)): print hex(i)",
"if offset == \\ 2*(hundreds * 0x100 + twice) + once: return once,",
"self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\")",
"debug printing activated? @staticmethod def none(*args): return None @staticmethod def debug(*ss): if Utils.verbose:",
"valid_bytes: for y in valid_bytes: if (x ^ y in valid_bytes): dups[x ^",
"= [x, y] # Dictionary of: bytes split as tuples of a validff",
"c in rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor operator with arbitrary",
"buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n,",
"self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\",",
"\"\" \\ for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3",
"word: is_validff = is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i",
"[x, y] # Dictionary of: bytes split as tuples of a validff byte",
"\"(%esp, %esi)\") return sc += (-len(sc) % 4) * \"G\" # \"G\" ->",
"== [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i]",
"4 = Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec = 4",
"(self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if",
"xor; \\ # of = lambda *args: reduce(xor, args, 0) # String of",
"exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\",
"base_code = self.code self.epilogue() self._assemble() code_offset = self.len - 1 if Utils.verbose: print",
"@self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word,",
"s in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z",
"else 32 code = Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\"",
"= 4 qword_size = 8 int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda",
"splits): splits[x ^ z] = [x, z] for x in valid_bytesff: for y",
"for i in range(words_nb)] for byte in word: i = 0 for x",
"valid_chars[0] # List of valid bytes valid_bytes = [ord(c) for c in valid_chars]",
"for i in word) if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] ==",
"char will represent 0xff zero = valid_chars[0] # List of valid bytes valid_bytes",
"for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split as tuples",
"0 for x in Xor.splits[byte]: words[i].append(x) i += 1 while (i < words_nb):",
"\"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\"",
"validff byte and valid bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]]",
"error: 64 bits support not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx,",
"Pushes the 4-bytes word using alphanumeric opcodes only (Requires %esi = -0x34, %dl",
"in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro()",
"dec %esp\").len incpoppushdec = 4 for hundreds in range(0x100): if hundreds == 1:",
"((chr(i) if i != 0xff else Xor.zero) for i in bytes[::-1]) return \"$0x\"",
"range(words_nb)] for byte in word: i = 0 for x in Xor.splits[byte]: words[i].append(x)",
"self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\")",
"ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa()",
"and z are valid bytes and that 2 * (x * 0x100 +",
"once, twice, hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32):",
"^ z in splits): splits[x ^ y ^ z] = [x, y, z]",
"if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \\",
"xor operator with arbitrary arity \"\"\" acc = 0 for arg in args:",
"+ 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words])",
"replacing the byte 0xff by a valid one \"\"\" assert(len(bytes) <= arch /",
"self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size =",
"%esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\",
"bytes into its integer representation, but replacing the byte 0xff by a valid",
"z verifying that y and z are valid bytes and that 2 *",
"esi, edi = \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size =",
"splits[x ^ z] = [x, z] for x in valid_bytesff: for y in",
"# Dictionary of: valid bytes split as tuples of valid bytes dups =",
"valid bytes valid_bytes = [ord(c) for c in valid_chars] # List of validff",
"<= arch / 8) rev_chars = \\ ((chr(i) if i != 0xff else",
"self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\", edx =",
"-> \"inc %edi\" Utils.debug(sc + \" : \" + str(len(sc)) + \" bytes.\")",
"[[] for i in range(words_nb)] for byte in word: i = 0 for",
"+ y) + z = offset + x + (x ? 4 :",
"self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg)",
"words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi, edi = \"\",",
"for i in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34",
"splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] = [z] splits[ord(zero)]",
"\"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self,",
"8 print \"'\" + argv[0] + \\ \"' error: 64 bits support not",
"\\ \"' error: 64 bits support not implemented yet\" exit(1) else: self.eax, self.ecx,",
"Utils.verbose: Xor.display() from sys import argv if len(argv) < 2 or len(argv) >",
"self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\",
"* (x * 0x100 + y) + z = offset + x +",
"arbitrary arity \"\"\" acc = 0 for arg in args: acc ^= arg",
"self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble = False if arch == 64:",
"+ \" bytes.\") all_words = [] for k in range(len(sc) / 4): all_words.append(",
"all_words.append( \\ Xor.split([ord(c) for c in sc[4 * k:4 * (k + 1)]]))",
"\\ for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3 else",
"# String of forbidden chars forbidden_chars = \"\" class Utils: verbose = False",
"will represent 0xff zero = valid_chars[0] # List of valid bytes valid_bytes =",
"splits[x ^ y ^ z] = [x, y, z] @staticmethod def display(): for",
"!= \"\\\\\" and c != \"x\" else \"\" \\ for c in argv[1]).decode(\"hex\")",
"\"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" + argv[0] +",
"of: bytes split as tuples of a validff byte and valid bytes splits",
"using alphanumeric opcodes only (Requires %esi = -0x34, %dl = 0x30 ^ 0xff",
"\"\"\" assert(len(word) == self.dword_size) is_validff = True for i in word: is_validff =",
"self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size =",
"\"G\" -> \"inc %edi\" Utils.debug(sc + \" : \" + str(len(sc)) + \"",
"Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100 + twice) + once: return",
"= is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff)",
"Xor.split([ord(c) for c in sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words) for",
"\" : \" + str(len(sc)) + \" bytes.\") all_words = [] for k",
"* 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\",",
"eax = \"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\", edx = \"%eax\",",
"valid bytes and that 2 * (x * 0x100 + y) + z",
"^= arg return acc # from functools import reduce; from operator import xor;",
"word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \\ \"(%esp,",
"for x in Xor.splits[byte]: words[i].append(x) i += 1 while (i < words_nb): x1,",
"in valid_bytes): dups[x ^ y] = [x, y] # Dictionary of: bytes split",
">= 0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def",
"range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) +",
"1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series of",
"offset == \\ 2*(hundreds * 0x100 + twice) + once: return once, twice,",
"in splits): splits[x ^ y ^ z] = [x, y, z] @staticmethod def",
"self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc,",
"= valid_chars[0] # List of valid bytes valid_bytes = [ord(c) for c in",
"valid_bytes = [ord(c) for c in valid_chars] # List of validff bytes (byte",
"in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod",
"\"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch):",
"\"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble = False if",
"def debug(*ss): if Utils.verbose: for s in ss: print s @staticmethod def offset_split_as_valids(offset):",
"= False if arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp,",
"Utils.verbose: for s in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x,",
"assembly import Assembly # String of forbidden chars forbidden_chars = \"\" class Utils:",
"0x100 + twice) + once: return once, twice, hundreds offset += 1 assert(False)",
"of(*args): \"\"\" xor operator with arbitrary arity \"\"\" acc = 0 for arg",
"splits): splits[x ^ y ^ z] = [x, y, z] @staticmethod def display():",
"self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\")",
"sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word)",
"+= (-len(sc) % 4) * \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc +",
"0xff zero = valid_chars[0] # List of valid bytes valid_bytes = [ord(c) for",
"= 0 # 4 = Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len",
"debug(*ss): if Utils.verbose: for s in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\"",
"in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split as tuples of valid",
"\"\" class Utils: verbose = False # Is debug printing activated? @staticmethod def",
"in word: i = 0 for x in Xor.splits[byte]: words[i].append(x) i += 1",
"a series of bytes into its integer representation, but replacing the byte 0xff",
"Is debug printing activated? @staticmethod def none(*args): return None @staticmethod def debug(*ss): if",
"@staticmethod def of(*args): \"\"\" xor operator with arbitrary arity \"\"\" acc = 0",
"+ string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent 0xff zero = valid_chars[0]",
"not (x ^ z in splits): splits[x ^ z] = [x, z] for",
"esp, ebp, esi, edi = \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"",
"1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0])",
"= True for i in word: is_validff = is_validff and \\ (i in",
"words_nb = max(len(Xor.splits[x]) for x in word) words = [[] for i in",
"self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \"(%esp, %esi)\") return sc +=",
"\"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset =",
"else \"\" \\ for c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) ==",
"for i in range(abs(n)): self(\"inc\" if n >= 0 else \"dec\", reg) @self.macro()",
"+ (x ? 4 : 0) \"\"\" hundreds = 0 # 4 =",
"0xff) for i in word) if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4]",
"+ hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx,",
"\"\"\" Input = word : byte array Output = words : (byte array)",
"word : byte array Output = words : (byte array) array, verifying that",
"in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c in sc[4 * k:4",
"byte array Output = words : (byte array) array, verifying that for j",
"Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)):",
"for z in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for",
"for x in valid_bytesff: for z in valid_bytes: if not (x ^ z",
"reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\")",
"pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric opcodes only (Requires %esi =",
"[] for k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c in",
"offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds:",
"acc ^= arg return acc # from functools import reduce; from operator import",
"self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\",",
"\"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue()",
"%esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec = 4 for hundreds in",
"z] for x in valid_bytesff: for y in valid_bytes: for z in valid_bytes:",
"@self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds,",
"self.popa() @self.macro() def rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if n >=",
"x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax,",
"[valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z in valid_bytes: if not",
"\"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code",
"@staticmethod def display(): for i in range(len(Xor.splits)): print hex(i) + \" = \"",
"Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word : byte array Output =",
"= self.code self.epilogue() self._assemble() code_offset = self.len - 1 if Utils.verbose: print self",
"is_validff = True for i in word: is_validff = is_validff and \\ (i",
"self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\")",
"= 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst)",
"and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for i",
"^ y ^ z in splits): splits[x ^ y ^ z] = [x,",
"operator import xor; \\ # of = lambda *args: reduce(xor, args, 0) #",
"str(34 + i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4):",
"added for xor completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] #",
"bytes split as tuples of valid bytes dups = {} for x in",
"i in range(words_nb)] for byte in word: i = 0 for x in",
"x in Xor.splits[byte]: words[i].append(x) i += 1 while (i < words_nb): x1, x2",
"ecx = \"%edx\", edx = \"%eax\", \\ esi = \"%eax\", edi = \"%eax\",",
"\\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for i in",
"for c in valid_chars] # List of validff bytes (byte 0xff added for",
"== 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:])",
"+ str(34 + i) + \"(%esp, %esi)\") return sc += (-len(sc) % 4)",
"range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def",
"valid bytes split as tuples of valid bytes dups = {} for x",
"\"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" + argv[0] + \\ \"' error:",
"\"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset",
"are valid bytes and that 2 * (x * 0x100 + y) +",
"init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx",
"print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that y",
": (byte array) array, verifying that for j in range(len(word)): word[j] == Xor.of(words[i][j]",
"esi = \"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3,",
"@staticmethod def none(*args): return None @staticmethod def debug(*ss): if Utils.verbose: for s in",
"\"%rdi\" self.int_size = 8 print \"'\" + argv[0] + \\ \"' error: 64",
"1: offset += incpoppushdec for once in Xor.valid_bytes: for twice in Xor.valid_bytes: if",
"for i in word: is_validff = is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff)",
"if i != 0xff else Xor.zero) for i in bytes[::-1]) return \"$0x\" +",
"32): \"\"\" Converts a series of bytes into its integer representation, but replacing",
"False # Is debug printing activated? @staticmethod def none(*args): return None @staticmethod def",
"+= incpoppushdec for once in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset ==",
"return sc += (-len(sc) % 4) * \"G\" # \"G\" -> \"inc %edi\"",
"arg return acc # from functools import reduce; from operator import xor; \\",
"words) return words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi, edi",
"word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def",
"\"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble()",
"\"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes",
"= [[] for i in range(words_nb)] for byte in word: i = 0",
"1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp,",
"= \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8",
"@self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx)",
"if c != \"\\\\\" and c != \"x\" else \"\" \\ for c",
"< 2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc",
"@staticmethod def debug(*ss): if Utils.verbose: for s in ss: print s @staticmethod def",
"display(): for i in range(len(Xor.splits)): print hex(i) + \" = \" + \\",
"edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi)",
"= \\ ((chr(i) if i != 0xff else Xor.zero) for i in bytes[::-1])",
"\" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in word) words",
"of bytes into its integer representation, but replacing the byte 0xff by a",
"verbose = False # Is debug printing activated? @staticmethod def none(*args): return None",
"in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word : byte array Output",
"Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\",",
"\"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" +",
"for y in valid_bytes: for z in valid_bytes: if not (x ^ y",
"# List of valid bytes valid_bytes = [ord(c) for c in valid_chars] #",
"# of = lambda *args: reduce(xor, args, 0) # String of valid chars",
"\"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg",
"(edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\")",
"+ \"(%esp, %esi)\") return sc += (-len(sc) % 4) * \"G\" # \"G\"",
"Dictionary of: valid bytes split as tuples of valid bytes dups = {}",
"\"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c != \"\\\\\" and c !=",
"all_words = [] for k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for",
"or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c",
"* (k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word",
"split as tuples of a validff byte and valid bytes splits = {}",
"= False # Is debug printing activated? @staticmethod def none(*args): return None @staticmethod",
"arch = 32): \"\"\" Converts a series of bytes into its integer representation,",
"valid_bytesff: for y in valid_bytes: for z in valid_bytes: if not (x ^",
"self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\",",
"in valid_bytes: if not (x ^ y ^ z in splits): splits[x ^",
"bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes:",
"self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word",
"return words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi, edi =",
"List of valid bytes valid_bytes = [ord(c) for c in valid_chars] # List",
"\\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\",",
"chars forbidden_chars = \"\" class Utils: verbose = False # Is debug printing",
"? 4 : 0) \"\"\" hundreds = 0 # 4 = Assembly()(\"inc %esp;",
"= 0 for arg in args: acc ^= arg return acc # from",
"\" bytes.\") all_words = [] for k in range(len(sc) / 4): all_words.append( \\",
"z] = [x, z] for x in valid_bytesff: for y in valid_bytes: for",
"(byte 0xff added for xor completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero,",
"+ \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in word) words =",
"%edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble = False if arch",
"%ecx; push %ecx; dec %esp\").len incpoppushdec = 4 for hundreds in range(0x100): if",
"class Xor: @staticmethod def of(*args): \"\"\" xor operator with arbitrary arity \"\"\" acc",
"bits support not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp,",
"0xff added for xor completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")]",
"split(word): \"\"\" Input = word : byte array Output = words : (byte",
")) @self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\")",
"# 4 = Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec =",
"(string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent 0xff zero =",
"edx, ebx, esp, ebp, esi, edi = \"\", \"\", \"\", \"\", \"\", \"\",",
"4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for",
"\\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] == 0xff:",
"Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word)",
"\"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds):",
"== Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word),",
"while (i < words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1]",
"x in valid_bytes: for y in valid_bytes: if (x ^ y in valid_bytes):",
"0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True for i in word: is_validff",
"= \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the",
"self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset = self.len - 1 if Utils.verbose:",
"x in valid_bytesff: for y in valid_bytes: for z in valid_bytes: if not",
"ff_nb = sum(int(i == 0xff) for i in word) if ff_nb == 4:",
"self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def",
"y in valid_bytes: if (x ^ y in valid_bytes): dups[x ^ y] =",
"representation, but replacing the byte 0xff by a valid one \"\"\" assert(len(bytes) <=",
"in sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]:",
"\"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs(",
"sum(int(i == 0xff) for i in word) if ff_nb == 4: self.pushl(\"%ecx\") return",
"def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that y and z are",
"self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax)",
"valid one \"\"\" assert(len(bytes) <= arch / 8) rev_chars = \\ ((chr(i) if",
"\\ ecx = \"%edx\", edx = \"%eax\", \\ esi = \"%eax\", edi =",
"if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\":",
"exit(1) sc = \"\".join(c if c != \"\\\\\" and c != \"x\" else",
"+ Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\",",
"ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"):",
"word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\")",
"< words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1",
"%esp\").len incpoppushdec = 4 for hundreds in range(0x100): if hundreds == 1: offset",
"64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\",",
"len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx",
"if Utils.verbose: Xor.display() from sys import argv if len(argv) < 2 or len(argv)",
"2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble = False if arch ==",
"in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i)",
"+= 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax, ecx, edx, ebx,",
"\"\"\" Pushes the 4-bytes word using alphanumeric opcodes only (Requires %esi = -0x34,",
"\"0x\" + str(34 + i) + \"(%esp, %esi)\") return sc += (-len(sc) %",
"import argv if len(argv) < 2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0],",
"(k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in",
"\"got \" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in word)",
"y, z] @staticmethod def display(): for i in range(len(Xor.splits)): print hex(i) + \"",
"len(argv) < 2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1)",
"self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc):",
"of validff bytes (byte 0xff added for xor completude) valid_bytesff = [ord(c) for",
"\\ ((chr(i) if i != 0xff else Xor.zero) for i in bytes[::-1]) return",
"= 2 dword_size = 4 qword_size = 8 int_size = 0 def prologue(self):",
"by a valid one \"\"\" assert(len(bytes) <= arch / 8) rev_chars = \\",
"= Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec = 4 for",
"@staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series of bytes into",
"code print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \" + str(code.len) + \"",
"valid_bytesff: for z in valid_bytes: if not (x ^ z in splits): splits[x",
"self.code self.epilogue() self._assemble() code_offset = self.len - 1 if Utils.verbose: print self self.code",
"Xor: @staticmethod def of(*args): \"\"\" xor operator with arbitrary arity \"\"\" acc =",
"\\ self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4",
"def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series of bytes into its",
"in rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor operator with arbitrary arity",
"of valid bytes dups = {} for x in valid_bytes: for y in",
"i in word: is_validff = is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb",
"in word) if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]:",
"\"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c != \"\\\\\" and",
"push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric opcodes",
"self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\",",
"sc += (-len(sc) % 4) * \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc",
"= {} for x in valid_bytes: for y in valid_bytes: if (x ^",
"if not (x ^ y ^ z in splits): splits[x ^ y ^",
"\"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro()",
"\"\"\" acc = 0 for arg in args: acc ^= arg return acc",
"\"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4 self.prologue() self.push_sc(sc) base_code =",
"self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\",",
"\\ esi = \"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\")",
"in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in",
"import xor; \\ # of = lambda *args: reduce(xor, args, 0) # String",
"= -0x34, %dl = 0x30 ^ 0xff = 0xcf and %ecx = 0xffffffff)",
"in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for i in word) if",
"0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True for",
"if Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \" +",
"\"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\", edx",
"4-bytes word using alphanumeric opcodes only (Requires %esi = -0x34, %dl = 0x30",
"\"\", \"\", \"\", \"\" word_size = 2 dword_size = 4 qword_size = 8",
"= [x, z] for x in valid_bytesff: for y in valid_bytes: for z",
"x1, x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i",
"\"\", \"\", \"\" word_size = 2 dword_size = 4 qword_size = 8 int_size",
"reg): for i in range(abs(n)): self(\"inc\" if n >= 0 else \"dec\", reg)",
"+ Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\"",
"hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\")",
"== 3 else 32 code = Alphanumeric(sc, arch) if Utils.verbose: print code print",
"(Requires %esi = -0x34, %dl = 0x30 ^ 0xff = 0xcf and %ecx",
"# String of valid chars import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None,",
"self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" +",
"c != \"\\\\\" and c != \"x\" else \"\" \\ for c in",
"\"0x58\") def __init__(self, sc, arch): self.autoassemble = False if arch == 64: self.eax,",
"self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size",
"3 else 32 code = Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode",
"y] = [x, y] # Dictionary of: bytes split as tuples of a",
"edi = \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def",
"prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def",
"return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod def of(*args):",
"\"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\",",
"ecx, edx, ebx, esp, ebp, esi, edi = \"\", \"\", \"\", \"\", \"\",",
"if Utils.verbose: for s in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns",
"in valid_bytes: for z in valid_bytes: if not (x ^ y ^ z",
"c in sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words) for words in",
"= 8 print \"'\" + argv[0] + \\ \"' error: 64 bits support",
"self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\",
"/ 8) rev_chars = \\ ((chr(i) if i != 0xff else Xor.zero) for",
"+ \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] ==",
"i = 0 for x in Xor.splits[byte]: words[i].append(x) i += 1 while (i",
"for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for",
"\"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg)",
"\"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx)",
"\"\", \"\" word_size = 2 dword_size = 4 qword_size = 8 int_size =",
"argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3 else 32 code = Alphanumeric(sc,",
"\\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\",",
"in word: is_validff = is_validff and \\ (i in Xor.valid_bytesff) assert(is_validff) ff_nb =",
"# from functools import reduce; from operator import xor; \\ # of =",
"\"[arch]\" exit(1) sc = \"\".join(c if c != \"\\\\\" and c != \"x\"",
"self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i",
"for arg in args: acc ^= arg return acc # from functools import",
"^ y in valid_bytes): dups[x ^ y] = [x, y] # Dictionary of:",
"Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\")",
"z] = [x, y, z] @staticmethod def display(): for i in range(len(Xor.splits)): print",
"zero = valid_chars[0] # List of valid bytes valid_bytes = [ord(c) for c",
"def none(*args): return None @staticmethod def debug(*ss): if Utils.verbose: for s in ss:",
"for x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word : byte",
"\"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x",
"= \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\",",
"completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid",
"self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self,",
"\"' error: 64 bits support not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx,",
"in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100",
"of valid bytes valid_bytes = [ord(c) for c in valid_chars] # List of",
"word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\",
"verifying that for j in range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb))",
"Utils: verbose = False # Is debug printing activated? @staticmethod def none(*args): return",
"z in splits): splits[x ^ z] = [x, z] for x in valid_bytesff:",
"+ \" = \" + \\ \" ^ \".join(hex(x) for x in Xor.splits[i])",
"# \"G\" -> \"inc %edi\" Utils.debug(sc + \" : \" + str(len(sc)) +",
"for y in valid_bytes: if (x ^ y in valid_bytes): dups[x ^ y]",
"\"'\" + argv[0] + \\ \"' error: 64 bits support not implemented yet\"",
"range(abs(n)): self(\"inc\" if n >= 0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4,",
"= 4 for hundreds in range(0x100): if hundreds == 1: offset += incpoppushdec",
"4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\",",
"\"returning\", words) return words class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi,",
"string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent 0xff zero = valid_chars[0] #",
"= 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True for i in word:",
"valid char will represent 0xff zero = valid_chars[0] # List of valid bytes",
"self.int_size = 8 print \"'\" + argv[0] + \\ \"' error: 64 bits",
"of = lambda *args: reduce(xor, args, 0) # String of valid chars import",
"# List of validff bytes (byte 0xff added for xor completude) valid_bytesff =",
"byte 0xff by a valid one \"\"\" assert(len(bytes) <= arch / 8) rev_chars",
"self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\"",
"that y and z are valid bytes and that 2 * (x *",
"*args: reduce(xor, args, 0) # String of valid chars import string;\\ valid_chars =",
"\\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]),",
"= {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] =",
"self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax():",
"edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def",
"if len(argv) < 2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\"",
"arg in args: acc ^= arg return acc # from functools import reduce;",
"4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset = self.len - 1",
"= x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly):",
"self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\", \\ ecx",
"+ \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble = False",
"twice) + once: return once, twice, hundreds offset += 1 assert(False) @staticmethod def",
"self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2,",
"- 1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\",",
"@self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg)",
"\"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word using",
"\\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in word) words = [[]",
"= base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display() from sys",
"c in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3 else 32 code",
"sys import argv if len(argv) < 2 or len(argv) > 3: print \"Usage:\\n\\tpython\",",
"y) + z = offset + x + (x ? 4 : 0)",
"integer representation, but replacing the byte 0xff by a valid one \"\"\" assert(len(bytes)",
"for c in rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor operator with",
"y in valid_bytes): dups[x ^ y] = [x, y] # Dictionary of: bytes",
"Dictionary of: bytes split as tuples of a validff byte and valid bytes",
"\"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset)",
"args: acc ^= arg return acc # from functools import reduce; from operator",
"in valid_bytesff: for z in valid_bytes: if not (x ^ z in splits):",
"= \"%eax\", \\ esi = \"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\"",
"self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def",
"+ \\ \" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word): \"\"\"",
"+ \\ \"' error: 64 bits support not implemented yet\" exit(1) else: self.eax,",
"[0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] ==",
"in valid_bytes: for y in valid_bytes: if (x ^ y in valid_bytes): dups[x",
"^ y ^ z] = [x, y, z] @staticmethod def display(): for i",
"from functools import reduce; from operator import xor; \\ # of = lambda",
"1 while (i < words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i -",
"= words : (byte array) array, verifying that for j in range(len(word)): word[j]",
"valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split as tuples of valid bytes",
"+= 1 while (i < words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i",
"a validff byte and valid bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1],",
"sc = \"\".join(c if c != \"\\\\\" and c != \"x\" else \"\"",
"for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb",
"esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro()",
"if not (x ^ z in splits): splits[x ^ z] = [x, z]",
"self.autoassemble = False if arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp,",
"%dl = 0x30 ^ 0xff = 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word)",
"y ^ z in splits): splits[x ^ y ^ z] = [x, y,",
"(x * 0x100 + y) + z = offset + x + (x",
"(x ^ y ^ z in splits): splits[x ^ y ^ z] =",
"= \"%edx\", edx = \"%eax\", \\ esi = \"%eax\", edi = \"%eax\", \\",
"Input = word : byte array Output = words : (byte array) array,",
"= 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True",
"forbidden_chars) # One valid char will represent 0xff zero = valid_chars[0] # List",
"i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0):",
"splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z]",
"\" + \\ \" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word):",
"* 0x100 + twice) + once: return once, twice, hundreds offset += 1",
"zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro()",
"\"\"\" hundreds = 0 # 4 = Assembly()(\"inc %esp; pop %ecx; push %ecx;",
"edx = \"%eax\", \\ esi = \"%eax\", edi = \"%eax\", \\ ebp =",
"c != \"x\" else \"\" \\ for c in argv[1]).decode(\"hex\") arch = int(argv[2])",
"0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \"(%esp, %esi)\") return sc",
"import reduce; from operator import xor; \\ # of = lambda *args: reduce(xor,",
"(i < words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1] =",
"in valid_chars] # List of validff bytes (byte 0xff added for xor completude)",
"ord(zero)] for x in valid_bytesff: for z in valid_bytes: if not (x ^",
"%ecx; dec %esp\").len incpoppushdec = 4 for hundreds in range(0x100): if hundreds ==",
"= max(len(Xor.splits[x]) for x in word) words = [[] for i in range(words_nb)]",
"word) words = [[] for i in range(words_nb)] for byte in word: i",
"4) * \"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc + \" : \"",
"+ \" : \" + str(len(sc)) + \" bytes.\") all_words = [] for",
"\" = \" + \\ \" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod",
"= sum(int(i == 0xff) for i in word) if ff_nb == 4: self.pushl(\"%ecx\")",
"self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self,",
"= [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split",
"i in range(len(Xor.splits)): print hex(i) + \" = \" + \\ \" ^",
"pop %ecx; push %ecx; dec %esp\").len incpoppushdec = 4 for hundreds in range(0x100):",
"if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \"(%esp,",
"+ str(len(sc)) + \" bytes.\") all_words = [] for k in range(len(sc) /",
"print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose:",
"if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2):",
"\"\", \"\", \"\", \"\", \"\", \"\" word_size = 2 dword_size = 4 qword_size",
"class Utils: verbose = False # Is debug printing activated? @staticmethod def none(*args):",
"argv[0] + \\ \"' error: 64 bits support not implemented yet\" exit(1) else:",
"operator with arbitrary arity \"\"\" acc = 0 for arg in args: acc",
"1 if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ ==",
"\"\"\" Returns x, y, z verifying that y and z are valid bytes",
"in valid_bytesff: for y in valid_bytes: for z in valid_bytes: if not (x",
"range(0x100): if hundreds == 1: offset += incpoppushdec for once in Xor.valid_bytes: for",
"self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\", \"0x58\") def __init__(self, sc, arch): self.autoassemble",
"= int(argv[2]) if len(argv) == 3 else 32 code = Alphanumeric(sc, arch) if",
"self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\")",
"\"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" + argv[0] + \\",
"arch = int(argv[2]) if len(argv) == 3 else 32 code = Alphanumeric(sc, arch)",
"splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff: for",
"argv if len(argv) < 2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\",",
"max(len(Xor.splits[x]) for x in word) words = [[] for i in range(words_nb)] for",
"s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that y and",
"dups = {} for x in valid_bytes: for y in valid_bytes: if (x",
"implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi",
"code = Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii",
"print code print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \" + str(code.len) +",
"for x in word) words = [[] for i in range(words_nb)] for byte",
"forbidden_chars = \"\" class Utils: verbose = False # Is debug printing activated?",
"0xff else Xor.zero) for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c",
"qword_size = 8 int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst:",
"Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for i in word) if ff_nb",
"offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that y and z are valid",
"== 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \\ \"(%esp, %esi)\")",
"return once, twice, hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch =",
"\"G\" # \"G\" -> \"inc %edi\" Utils.debug(sc + \" : \" + str(len(sc))",
"* k:4 * (k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\",
"arity \"\"\" acc = 0 for arg in args: acc ^= arg return",
"of: valid bytes split as tuples of valid bytes dups = {} for",
"words[i].append(x) i += 1 while (i < words_nb): x1, x2 = Xor.dups[words[i -",
"into its integer representation, but replacing the byte 0xff by a valid one",
"that 2 * (x * 0x100 + y) + z = offset +",
"0 # 4 = Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec",
"one \"\"\" assert(len(bytes) <= arch / 8) rev_chars = \\ ((chr(i) if i",
"self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display() from sys import argv",
"word) words_nb = max(len(Xor.splits[x]) for x in word) words = [[] for i",
"+ i) + \"(%esp, %esi)\") return sc += (-len(sc) % 4) * \"G\"",
"in Xor.splits[byte]: words[i].append(x) i += 1 while (i < words_nb): x1, x2 =",
"\"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def",
"for c in sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words) for words",
"valid_bytesff[1]] for z in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)]",
"string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char will",
"def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\",",
"in valid_bytes: if not (x ^ z in splits): splits[x ^ z] =",
"and c != \"x\" else \"\" \\ for c in argv[1]).decode(\"hex\") arch =",
"i) + \"(%esp, %esi)\") return sc += (-len(sc) % 4) * \"G\" #",
"\"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax()",
"return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\"",
"word_size = 2 dword_size = 4 qword_size = 8 int_size = 0 def",
"\"\".join(c if c != \"\\\\\" and c != \"x\" else \"\" \\ for",
"Assembly # String of forbidden chars forbidden_chars = \"\" class Utils: verbose =",
"range(len(Xor.splits)): print hex(i) + \" = \" + \\ \" ^ \".join(hex(x) for",
"[0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1],",
"for z in valid_bytes: if not (x ^ y ^ z in splits):",
"valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent",
"self.xorl(\"0x30(%esp, %esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg =",
"self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\",
"else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\",",
"32 code = Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\" print",
"edi = \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size = 2",
"k:4 * (k + 1)]])) Utils.debug(all_words) for words in all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for",
"for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\")",
"valid_bytes: if (x ^ y in valid_bytes): dups[x ^ y] = [x, y]",
"self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) +",
"reduce(xor, args, 0) # String of valid chars import string;\\ valid_chars = \\",
"in word) words = [[] for i in range(words_nb)] for byte in word:",
"xor completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of:",
"False if arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi,",
"(byte array) array, verifying that for j in range(len(word)): word[j] == Xor.of(words[i][j] for",
"for x in valid_bytes: for y in valid_bytes: if (x ^ y in",
"range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) +",
"words : (byte array) array, verifying that for j in range(len(word)): word[j] ==",
"= \"%eax\", edi = \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\")",
"if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\"",
"= [ord(c) for c in valid_chars] # List of validff bytes (byte 0xff",
"# Is debug printing activated? @staticmethod def none(*args): return None @staticmethod def debug(*ss):",
"y, z verifying that y and z are valid bytes and that 2",
"= lambda *args: reduce(xor, args, 0) # String of valid chars import string;\\",
"\\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word",
"+ str(34 + i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in",
"i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb =",
"4): all_words.append( \\ Xor.split([ord(c) for c in sc[4 * k:4 * (k +",
": 0) \"\"\" hundreds = 0 # 4 = Assembly()(\"inc %esp; pop %ecx;",
"len(argv) == 3 else 32 code = Alphanumeric(sc, arch) if Utils.verbose: print code",
"of forbidden chars forbidden_chars = \"\" class Utils: verbose = False # Is",
"self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\",",
"word using alphanumeric opcodes only (Requires %esi = -0x34, %dl = 0x30 ^",
"Alphanumeric(sc, arch) if Utils.verbose: print code print \"alphanumeric_shellcode =\" print code.ascii print \"Total:",
"Returns x, y, z verifying that y and z are valid bytes and",
"for i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class",
"bytes valid_bytes = [ord(c) for c in valid_chars] # List of validff bytes",
"\"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\", edx = \"%eax\", \\ esi",
"args, 0) # String of valid chars import string;\\ valid_chars = \\ (string.digits",
"= 0x30 ^ 0xff = 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) ==",
"0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] == 0xff:",
"hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\")",
"sc, arch): self.autoassemble = False if arch == 64: self.eax, self.ecx, self.edx, self.ebx,",
"(i in Xor.valid_bytesff) assert(is_validff) ff_nb = sum(int(i == 0xff) for i in word)",
"= \"\".join(c if c != \"\\\\\" and c != \"x\" else \"\" \\",
"i in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 +",
"validff bytes (byte 0xff added for xor completude) valid_bytesff = [ord(c) for c",
"# Dictionary of: bytes split as tuples of a validff byte and valid",
"z in valid_bytes: if not (x ^ y ^ z in splits): splits[x",
"= \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent 0xff",
"int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\",
"0 for arg in args: acc ^= arg return acc # from functools",
"= \"%edx\", ebx = \"%edx\", \\ ecx = \"%edx\", edx = \"%eax\", \\",
"self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp,",
"for hundreds in range(0x100): if hundreds == 1: offset += incpoppushdec for once",
"words = [[] for i in range(words_nb)] for byte in word: i =",
"assert(is_validff) ff_nb = sum(int(i == 0xff) for i in word) if ff_nb ==",
"ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" +",
"none(*args): return None @staticmethod def debug(*ss): if Utils.verbose: for s in ss: print",
"self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro()",
"self.len - 1 if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if",
"words[i].append(x2) i += 1 Utils.debug(\"Debug(split)\", \"returning\", words) return words class Alphanumeric(Assembly): eax, ecx,",
"all_words[::-1]: Utils.debug([Utils.to_hex_wordff(word) \\ for word in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1,",
"\\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid char will represent 0xff zero",
"True for i in word: is_validff = is_validff and \\ (i in Xor.valid_bytesff)",
"return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in",
"self.epilogue() self._assemble() code_offset = self.len - 1 if Utils.verbose: print self self.code =",
"self.int_size = 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset = self.len",
"dups[x ^ y] = [x, y] # Dictionary of: bytes split as tuples",
"= \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\" word_size = 2 dword_size",
"0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \\ \"(%esp, %esi)\") return",
"== \"__main__\": if Utils.verbose: Xor.display() from sys import argv if len(argv) < 2",
"Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x]) for x in",
"self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax = \"%edx\", ebx = \"%edx\",",
"def pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric opcodes only (Requires %esi",
"rev_chars = \\ ((chr(i) if i != 0xff else Xor.zero) for i in",
"if n >= 0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg)",
"for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero),",
"its integer representation, but replacing the byte 0xff by a valid one \"\"\"",
"z are valid bytes and that 2 * (x * 0x100 + y)",
"verifying that y and z are valid bytes and that 2 * (x",
"set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried)",
"self._assemble() code_offset = self.len - 1 if Utils.verbose: print self self.code = base_code",
"valid_bytes: for z in valid_bytes: if not (x ^ y ^ z in",
": byte array Output = words : (byte array) array, verifying that for",
"\".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input = word :",
"forbidden chars forbidden_chars = \"\" class Utils: verbose = False # Is debug",
"0) \"\"\" hundreds = 0 # 4 = Assembly()(\"inc %esp; pop %ecx; push",
"valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1], ord(zero)] for x in valid_bytesff:",
"0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) ))",
"sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric opcodes only",
"= 4 self.prologue() self.push_sc(sc) base_code = self.code self.epilogue() self._assemble() code_offset = self.len -",
"= 0 for x in Xor.splits[byte]: words[i].append(x) i += 1 while (i <",
"\\ Xor.split([ord(c) for c in sc[4 * k:4 * (k + 1)]])) Utils.debug(all_words)",
"for once in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset == \\ 2*(hundreds",
"3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c !=",
"printing activated? @staticmethod def none(*args): return None @staticmethod def debug(*ss): if Utils.verbose: for",
"[ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split as",
"split as tuples of valid bytes dups = {} for x in valid_bytes:",
"@self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\", \"%al\") self.set_regs( eax =",
"i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i]",
"%esi)\", \"%esp\") self.init_regs() self.pushl(\"%esp\") self.incl(\"%esp\") self.popl(\"%ecx\") self.rep_add(2, \"%ecx\") self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\")",
"self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if n",
"String of valid chars import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars)",
"self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if word[i] == 0xff: self.xorb(\"%dl\",",
"eax, ecx, edx, ebx, esp, ebp, esi, edi = \"\", \"\", \"\", \"\",",
"represent 0xff zero = valid_chars[0] # List of valid bytes valid_bytes = [ord(c)",
"valid_bytes: if not (x ^ z in splits): splits[x ^ z] = [x,",
"and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True for i",
"\"\".join(c.encode(\"hex\") for c in rev_chars) class Xor: @staticmethod def of(*args): \"\"\" xor operator",
"def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx)",
"chars import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) # One valid",
"assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series of bytes",
"0x100 + y) + z = offset + x + (x ? 4",
"class Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi, edi = \"\", \"\",",
"hundreds in range(0x100): if hundreds == 1: offset += incpoppushdec for once in",
"= Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1 words[i].append(x2) i += 1",
"for z in valid_bytes: if not (x ^ z in splits): splits[x ^",
"%edi\" Utils.debug(sc + \" : \" + str(len(sc)) + \" bytes.\") all_words =",
"hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts",
"self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\"",
"Output = words : (byte array) array, verifying that for j in range(len(word)):",
"if __name__ == \"__main__\": if Utils.verbose: Xor.display() from sys import argv if len(argv)",
"offset + x + (x ? 4 : 0) \"\"\" hundreds = 0",
"def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro()",
"dst: \\ Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\" +",
"\"\" word_size = 2 dword_size = 4 qword_size = 8 int_size = 0",
"byte and valid bytes splits = {} splits[0xff] = [0xff, valid_bytesff[1], valid_bytesff[1]] for",
"print hex(i) + \" = \" + \\ \" ^ \".join(hex(x) for x",
"in valid_bytes: if (x ^ y in valid_bytes): dups[x ^ y] = [x,",
"8 int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\ Utils.none(self.push(src),",
"== 1: offset += incpoppushdec for once in Xor.valid_bytes: for twice in Xor.valid_bytes:",
"offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\" Converts a",
"{} for x in valid_bytes: for y in valid_bytes: if (x ^ y",
"alphanumeric opcodes only (Requires %esi = -0x34, %dl = 0x30 ^ 0xff =",
"as tuples of a validff byte and valid bytes splits = {} splits[0xff]",
"self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word))",
"self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\") self.xorb(\"$0x64\", \"%al\") self.xorb(\"%al\", hex(offset) + \"(%ebp, %edx, 2)\") self(\".byte\",",
"self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if",
"words_nb): x1, x2 = Xor.dups[words[i - 1][-1]] words[i - 1][-1] = x1 words[i].append(x2)",
"hex(edx)) if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds)",
"valid bytes dups = {} for x in valid_bytes: for y in valid_bytes:",
"\"0x\" + str(34 + i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i",
"bytes dups = {} for x in valid_bytes: for y in valid_bytes: if",
"+ x + (x ? 4 : 0) \"\"\" hundreds = 0 #",
"if hundreds == 1: offset += incpoppushdec for once in Xor.valid_bytes: for twice",
"c in valid_chars.replace(zero, \"\\xff\")] # Dictionary of: valid bytes split as tuples of",
"(aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\", \"%esp\")",
"4 for hundreds in range(0x100): if hundreds == 1: offset += incpoppushdec for",
"def push_sc(self, sc): @self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric",
"\"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if word[i] == 0xff: self.xorb(\"%dl\",",
"= offset + x + (x ? 4 : 0) \"\"\" hundreds =",
"Xor.splits[byte]: words[i].append(x) i += 1 while (i < words_nb): x1, x2 = Xor.dups[words[i",
"self.push(edx) self.push(ebx) self.push(buried) self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i",
"0 else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs():",
"= \"%eax\", \\ ebp = \"%ecx\" ) self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp",
"hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\", \"%eax\")",
"i in range(abs(n)): self(\"inc\" if n >= 0 else \"dec\", reg) @self.macro() def",
"for s in ss: print s @staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y,",
"import Assembly # String of forbidden chars forbidden_chars = \"\" class Utils: verbose",
"push %ecx; dec %esp\").len incpoppushdec = 4 for hundreds in range(0x100): if hundreds",
"of valid chars import string;\\ valid_chars = \\ (string.digits + string.ascii_letters).translate(None, forbidden_chars) #",
"x in valid_bytesff: for z in valid_bytes: if not (x ^ z in",
"for i in range(2): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34",
"arch): self.autoassemble = False if arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\",
"@staticmethod def offset_split_as_valids(offset): \"\"\" Returns x, y, z verifying that y and z",
"i in bytes[::-1]) return \"$0x\" + \"\".join(c.encode(\"hex\") for c in rev_chars) class Xor:",
"Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\",
"\"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg,",
"popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp, %esi)\",",
"self.dword_size) is_validff = True for i in word: is_validff = is_validff and \\",
"+ i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for i in range(4): if",
"self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\",
"%ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff = True for i in",
"2 or len(argv) > 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc =",
"word) if ff_nb == 4: self.pushl(\"%ecx\") return if word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\")",
"offset += incpoppushdec for once in Xor.valid_bytes: for twice in Xor.valid_bytes: if offset",
"\\ 2*(hundreds * 0x100 + twice) + once: return once, twice, hundreds offset",
"self.esp, self.ebp, self.esi, self.edi = \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\",",
"valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] = [z] splits[ord(zero)] = [valid_bytesff[1], valid_bytesff[1],",
"valid_bytesff[1], ord(zero)] for x in valid_bytesff: for z in valid_bytes: if not (x",
"\"\"\" assert(len(bytes) <= arch / 8) rev_chars = \\ ((chr(i) if i !=",
"assert(len(word) == self.dword_size) is_validff = True for i in word: is_validff = is_validff",
"i in range(4): if word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 +",
"self.push(ebp) self.push(esi) self.push(edi) self.popa() @self.macro() def rep_add(n, reg): for i in range(abs(n)): self(\"inc\"",
"self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def epilogue (self, offset=ord(Xor.zero),",
"self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi = \\ \"%rax\", \"%rbx\",",
"for twice in Xor.valid_bytes: if offset == \\ 2*(hundreds * 0x100 + twice)",
"\\ \" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input",
"tuples of a validff byte and valid bytes splits = {} splits[0xff] =",
"for j in range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\",",
"reduce; from operator import xor; \\ # of = lambda *args: reduce(xor, args,",
"@self.macro() def pushff(word): \"\"\" Pushes the 4-bytes word using alphanumeric opcodes only (Requires",
") self.incl(\"%ebx\") self.rep_add(3, \"%edx\") @self.macro() def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp,",
"def popl_esp (aux_reg = \"%eax\"): self.pmov(\"%esp\", aux_reg) self.xorl(\"0x34(%esp, %esi)\", aux_reg) self.pmov(aux_reg, aux_reg) self.xorl(\"0x30(%esp,",
"= \\ \"%eax\", \"%ebx\", \"%ecx\", \"%edx\",\\ \"%esp\", \"%ebp\", \"%esi\", \"%edi\" self.int_size = 4",
"- 1 if Utils.verbose: print self self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__",
"int(argv[2]) if len(argv) == 3 else 32 code = Alphanumeric(sc, arch) if Utils.verbose:",
"def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\")",
"pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\", \"%edx\") self.xorb(\"$0x33\",",
"arch == 64: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi =",
"^ z] = [x, z] for x in valid_bytesff: for y in valid_bytes:",
"def rep_add(n, reg): for i in range(abs(n)): self(\"inc\" if n >= 0 else",
"0xff = 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff =",
"x + (x ? 4 : 0) \"\"\" hundreds = 0 # 4",
"[ord(c) for c in valid_chars] # List of validff bytes (byte 0xff added",
"dword_size = 4 qword_size = 8 int_size = 0 def prologue(self): self.macro \\",
"the 4-bytes word using alphanumeric opcodes only (Requires %esi = -0x34, %dl =",
"ecx=\"%ecx\", edx=\"%edx\", ebx=\"%ebx\",\\ ebp=\"%ebp\", esi=\"%esi\", edi=\"%edi\", buried=\"%eax\"): self.push(eax) self.push(ecx) self.push(edx) self.push(ebx) self.push(buried) self.push(ebp)",
"hundreds == 1: offset += incpoppushdec for once in Xor.valid_bytes: for twice in",
"self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word,",
"in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \" + \\ Utils.to_hex_wordff(word), word) words_nb = max(len(Xor.splits[x])",
"\\ # of = lambda *args: reduce(xor, args, 0) # String of valid",
"Alphanumeric(Assembly): eax, ecx, edx, ebx, esp, ebp, esi, edi = \"\", \"\", \"\",",
"support not implemented yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp,",
"Utils.none(self.push(src), \\ self.popl(dst) )) @self.macro() def zero_eax(): word = \"$0x\" + Xor.zero.encode(\"hex\") *",
"for xor completude) valid_bytesff = [ord(c) for c in valid_chars.replace(zero, \"\\xff\")] # Dictionary",
"print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c != \"\\\\\"",
"functools import reduce; from operator import xor; \\ # of = lambda *args:",
"\"\\\\\" and c != \"x\" else \"\" \\ for c in argv[1]).decode(\"hex\") arch",
"self.esi, self.edi = \\ \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size",
"and that 2 * (x * 0x100 + y) + z = offset",
"y] # Dictionary of: bytes split as tuples of a validff byte and",
"0x30 ^ 0xff = 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size)",
"print \"alphanumeric_shellcode =\" print code.ascii print \"Total: \" + str(code.len) + \" bytes.\"",
"(x ^ z in splits): splits[x ^ z] = [x, z] for x",
"in range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\" Utils.debug(\"Debug(split)\", \"got \"",
"\\ \"0x\" + str(34 + i) + \\ \"(%esp, %esi)\") return self.pushl(Utils.to_hex_wordff(word)) for",
"== 0xff) for i in word) if ff_nb == 4: self.pushl(\"%ecx\") return if",
"word[2:4] == [0xff, 0xff]: self.pushw(\"%cx\") self.pushw(\"$0x\" + Utils.to_hex_wordff(word)[7:]) for i in range(2): if",
"== 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \"(%esp, %esi)\") return",
"bytes (byte 0xff added for xor completude) valid_bytesff = [ord(c) for c in",
"else \"dec\", reg) @self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\")",
"= 32): \"\"\" Converts a series of bytes into its integer representation, but",
"for x in valid_bytesff: for y in valid_bytes: for z in valid_bytes: if",
"self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display() from sys import argv if",
"c in valid_chars] # List of validff bytes (byte 0xff added for xor",
"that for j in range(len(word)): word[j] == Xor.of(words[i][j] for i in range(words_nb)) \"\"\"",
"z = offset + x + (x ? 4 : 0) \"\"\" hundreds",
"Xor.display() from sys import argv if len(argv) < 2 or len(argv) > 3:",
"> 3: print \"Usage:\\n\\tpython\", argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c",
"= [0xff, valid_bytesff[1], valid_bytesff[1]] for z in valid_bytes: splits[z] = [z] splits[ord(zero)] =",
"-0x34, %dl = 0x30 ^ 0xff = 0xcf and %ecx = 0xffffffff) \"\"\"",
"^ z] = [x, y, z] @staticmethod def display(): for i in range(len(Xor.splits)):",
"\"%rcx\", \"%rdx\",\\ \"%rsp\", \"%rbp\", \"%rsi\", \"%rdi\" self.int_size = 8 print \"'\" + argv[0]",
"2 dword_size = 4 qword_size = 8 int_size = 0 def prologue(self): self.macro",
"if hundreds: self.incl(\"%esp\") self.popl(\"%edx\") self.rep_add(hundreds, \"%edx\") self.pushl(\"%edx\") self.decl(\"%esp\") self.popl(\"%edx\") self.push(\"%esp\") self.set_edx(edx, hundreds) self.pmov(\"%ecx\",",
"== \\ 2*(hundreds * 0x100 + twice) + once: return once, twice, hundreds",
"\"\\xff\")] # Dictionary of: valid bytes split as tuples of valid bytes dups",
"tuples of valid bytes dups = {} for x in valid_bytes: for y",
"^ y] = [x, y] # Dictionary of: bytes split as tuples of",
"in words]) self.pushff(words[0]) self.popl(\"%eax\") for i in range(1, len(words)): self.xorl(Utils.to_hex_wordff(words[i]), \"%eax\") self.pushl(\"%eax\") def",
"word[i] == 0xff: self.xorb(\"%dl\", \\ \"0x\" + str(34 + i) + \"(%esp, %esi)\")",
"as tuples of valid bytes dups = {} for x in valid_bytes: for",
"self.pushl(\"%ecx\") self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word):",
"epilogue (self, offset=ord(Xor.zero), edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx))",
"if (x ^ y in valid_bytes): dups[x ^ y] = [x, y] #",
"= word : byte array Output = words : (byte array) array, verifying",
"\"$0x\" + Xor.zero.encode(\"hex\") * 4 self.pmov(word, \"%eax\") self.xorl(word, \"%eax\") @self.macro() def set_regs(eax=\"%eax\", ecx=\"%ecx\",",
"String of forbidden chars forbidden_chars = \"\" class Utils: verbose = False #",
"= 8 int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src, dst: \\",
"Assembly()(\"inc %esp; pop %ecx; push %ecx; dec %esp\").len incpoppushdec = 4 for hundreds",
"def of(*args): \"\"\" xor operator with arbitrary arity \"\"\" acc = 0 for",
"not (x ^ y ^ z in splits): splits[x ^ y ^ z]",
"@self.macro() def pop_eip(reg): self.rep_add(-4, \"%esp\") self.popl(reg) @self.macro() def init_regs(): self.pop_eip(\"%ecx\") self.zero_eax() self.decl(\"%eax\") self.pmov(\"%eax\",",
"edx=ord(Xor.zero), hundreds=0): @self.macro() def set_edx (edx, hundreds): self.push(\"$\" + hex(edx)) if hundreds: self.incl(\"%esp\")",
"base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display() from sys import",
"argv[0], \"shellcode\", \"[arch]\" exit(1) sc = \"\".join(c if c != \"\\\\\" and c",
"array, verifying that for j in range(len(word)): word[j] == Xor.of(words[i][j] for i in",
"One valid char will represent 0xff zero = valid_chars[0] # List of valid",
"^ 0xff = 0xcf and %ecx = 0xffffffff) \"\"\" assert(len(word) == self.dword_size) is_validff",
"yet\" exit(1) else: self.eax, self.ecx, self.edx, self.ebx, \\ self.esp, self.ebp, self.esi, self.edi =",
"self.code = base_code self.epilogue(*Utils.offset_split_as_valids(code_offset)) self._assemble() if __name__ == \"__main__\": if Utils.verbose: Xor.display() from",
"\" ^ \".join(hex(x) for x in Xor.splits[i]) @staticmethod def split(word): \"\"\" Input =",
"array) array, verifying that for j in range(len(word)): word[j] == Xor.of(words[i][j] for i",
"twice, hundreds offset += 1 assert(False) @staticmethod def to_hex_wordff(bytes, arch = 32): \"\"\"",
"def __init__(self, sc, arch): self.autoassemble = False if arch == 64: self.eax, self.ecx,",
"to_hex_wordff(bytes, arch = 32): \"\"\" Converts a series of bytes into its integer",
"@staticmethod def split(word): \"\"\" Input = word : byte array Output = words",
"\" + str(len(sc)) + \" bytes.\") all_words = [] for k in range(len(sc)",
"in argv[1]).decode(\"hex\") arch = int(argv[2]) if len(argv) == 3 else 32 code =",
"self.decl(\"%esp\") self.popl_esp(aux_reg = \"%ecx\") self.pmov(\"%eax\", \"%ecx\") def push_sc(self, sc): @self.macro() def pushff(word): \"\"\"",
"lambda *args: reduce(xor, args, 0) # String of valid chars import string;\\ valid_chars",
"None @staticmethod def debug(*ss): if Utils.verbose: for s in ss: print s @staticmethod",
"for k in range(len(sc) / 4): all_words.append( \\ Xor.split([ord(c) for c in sc[4",
"4 qword_size = 8 int_size = 0 def prologue(self): self.macro \\ (\"pmov\")(lambda src,"
] |
[
"by Django 3.1.2 on 2022-03-29 12:25 from django.db import migrations, models class Migration(migrations.Migration):",
"3.1.2 on 2022-03-29 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"[ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100),",
"2022-03-29 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home',",
"12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'),",
"# Generated by Django 3.1.2 on 2022-03-29 12:25 from django.db import migrations, models",
"'0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField(",
"dependencies = [ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web",
"Generated by Django 3.1.2 on 2022-03-29 12:25 from django.db import migrations, models class",
"migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2', field=models.CharField(default='Application Engineer', max_length=100),",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations = [",
"models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField(",
"model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2', field=models.CharField(default='Application Engineer', max_length=100), ),",
"= [ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer',",
"= [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2', field=models.CharField(default='Application",
"('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ]",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations",
"[ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2', field=models.CharField(default='Application Engineer',",
"on 2022-03-29 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations =",
"class Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home',",
"Django 3.1.2 on 2022-03-29 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2', field=models.CharField(default='Application Engineer', max_length=100), ), ]",
"<filename>home/migrations/0012_auto_20220329_0825.py # Generated by Django 3.1.2 on 2022-03-29 12:25 from django.db import migrations,",
"operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home', name='role2',",
"Migration(migrations.Migration): dependencies = [ ('home', '0011_home_degree_3_description'), ] operations = [ migrations.AddField( model_name='home', name='role1',",
"] operations = [ migrations.AddField( model_name='home', name='role1', field=models.CharField(default='Web Developer', max_length=100), ), migrations.AddField( model_name='home',"
] |
[
"current_user.id except AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating,",
"request, abort from flask_login import current_user, login_required from app import db, redis from",
"')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def",
"is None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value",
"comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author == current_user\\ or current_user.is_administrator:",
"current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm() if",
"import Article, Comment, Permission, Rating from app.decorators import permission_required, author_required from app.article import",
"name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title))",
"form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data",
"import db, redis from app.models import Article, Comment, Permission, Rating from app.decorators import",
"\\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>',",
"return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article =",
"\"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4,",
"TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return",
"avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm()",
"avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try:",
"= \" \".join(tag.name for tag in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form)",
"if rating is None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: #",
"= Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' '))",
"Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def",
"= redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings)",
"<gh_stars>0 from flask import flash, render_template, redirect, url_for, request, abort from flask_login import",
"Comment, Permission, Rating from app.decorators import permission_required, author_required from app.article import article as",
"article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建",
"current_user_rating = None try: current_user_id = current_user.id except AttributeError: current_user_id = None return",
"is None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article)",
"@login_required def comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment",
"@article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm() if form.validate_on_submit(): article =",
"len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating",
"= request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id)",
"= None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id",
"@author_required def edit(): form = EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, #",
"Rating from app.decorators import permission_required, author_required from app.article import article as article_blueprint from",
"# TODO: delete if article.name is None: article.name = form.title.data article.body = form.body.data",
"user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first()",
"app.article import article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import",
"form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id =",
"num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating",
"article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况",
"comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or",
"delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article',",
"0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating",
"= request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if",
"相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating",
"except AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id,",
"for tag in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required",
"comment.article.author == current_user\\ or comment.author == current_user\\ or current_user.is_administrator: db.session.delete(comment) flash('评论已经删除') return redirect(url_for('article.article',",
"rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id",
"import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\"",
"url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form =",
"ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None",
"\".join(tag.name for tag in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST'])",
"= Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating) return \"Rating",
"ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\"",
"app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article =",
"rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating =",
"db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article",
"= request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return",
"done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body",
"title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit()",
"@article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body =",
"# 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda rating:",
"redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name for",
"try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id = current_user.id",
"flask_login import current_user, login_required from app import db, redis from app.models import Article,",
"render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value']",
"from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article",
"from flask import flash, render_template, redirect, url_for, request, abort from flask_login import current_user,",
"if form.validate_on_submit(): article.title = form.title.data # TODO: delete if article.name is None: article.name",
"app import db, redis from app.models import Article, Comment, Permission, Rating from app.decorators",
"if form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() )",
"Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403)",
"current_user_id = current_user.id except AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating,",
"db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment =",
"!= article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user',",
"flash, render_template, redirect, url_for, request, abort from flask_login import current_user, login_required from app",
"article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data =",
"request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating",
"form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\",
"sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form",
"def edit(): form = EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, # TODO:",
"4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating =",
"and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO: delete if",
"edit(): form = EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete",
"@login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author",
"= Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS)",
"Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return",
"= rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id =",
"= article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id = current_user.id except AttributeError:",
"= current_user.id except AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating,",
"def comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment =",
"title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name for tag",
"# 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value",
"# 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all()",
"username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article)",
"tag in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def",
"= sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating = None try:",
"title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user",
"article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index",
"return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id =",
"request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建 rating =",
"flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article",
"user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id,",
"app.models import Article, Comment, Permission, Rating from app.decorators import permission_required, author_required from app.article",
"render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author",
"Article, Comment, Permission, Rating from app.decorators import permission_required, author_required from app.article import article",
"methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id']",
"# TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id)",
"try: avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating =",
"None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit()",
"= request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index'))",
"return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value =",
"abort from flask_login import current_user, login_required from app import db, redis from app.models",
"except ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating =",
"ratings)) / num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except",
"\" \".join(tag.name for tag in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating',",
"current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit',",
"article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id)",
"methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm() if form.validate_on_submit(): article = Article(",
"return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required",
"from app.models import Article, Comment, Permission, Rating from app.decorators import permission_required, author_required from",
"article.name is None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' '))",
"article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title",
"Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author == current_user\\ or current_user.is_administrator: db.session.delete(comment) flash('评论已经删除')",
"not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO: delete if article.name",
"import permission_required, author_required from app.article import article as article_blueprint from app.article.forms import EditArticleForm,",
") article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form)",
"Permission, Rating from app.decorators import permission_required, author_required from app.article import article as article_blueprint",
"db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id",
"Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\"",
"flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id)",
"from app import db, redis from app.models import Article, Comment, Permission, Rating from",
"sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating =",
"article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit():",
"or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author ==",
"login_required from app import db, redis from app.models import Article, Comment, Permission, Rating",
"def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER):",
"None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST'])",
"form = EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete name=form.title.data,",
"article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id",
"article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>')",
"not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST'])",
"methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body']",
"author_required from app.article import article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from",
"Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings =",
"modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author \\ and",
"body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return",
"article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value",
"as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>',",
"from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def",
"TODO: delete if article.name is None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data)",
"(redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404()",
"= form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改')",
"user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm() if form.validate_on_submit(): article",
"@author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not",
"build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article =",
"form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data)",
"if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next')",
"EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章",
"form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return",
"\"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) #",
"= article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id']",
"None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id =",
"current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required",
"'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user !=",
"新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating)",
"return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if",
"num_rating = len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating except",
"@article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or",
"rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id']",
"current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO: delete if article.name is",
"redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try:",
"@article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles",
"app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title):",
"article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data",
"= article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name for tag in article.tags)",
"'POST']) @author_required def edit(): form = EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data,",
"import article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index,",
"@article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and",
"current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or",
"== current_user\\ or comment.author == current_user\\ or current_user.is_administrator: db.session.delete(comment) flash('评论已经删除') return redirect(url_for('article.article', title=comment.article.title))",
"\\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO: delete",
"request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: #",
"render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def",
"\"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment(): user_id = request.form['user_id'] article_id = request.form['article_id']",
"ModifyArticleForm(article=article) if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title",
"= EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data,",
"else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title):",
"Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id)",
"url_for, request, abort from flask_login import current_user, login_required from app import db, redis",
"rating is None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改",
"import current_user, login_required from app import db, redis from app.models import Article, Comment,",
"form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id",
"abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def",
"None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value =",
"article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0,",
"or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form",
"from app.article import article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks",
"article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id = current_user.id except AttributeError: current_user_id",
"article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article',",
"article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm from app.tasks import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET'])",
"author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment",
"form.title.data # TODO: delete if article.name is None: article.name = form.title.data article.body =",
"def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author == current_user\\",
"app.decorators import permission_required, author_required from app.article import article as article_blueprint from app.article.forms import",
"rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value",
"article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\")",
"rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is",
"author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html',",
"获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda rating: rating.value,",
"form.category.data = article.category.id form.tags.data = \" \".join(tag.name for tag in article.tags) form.body.data =",
"request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next')",
"delete if article.name is None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags()",
"import build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404()",
"= Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author == current_user\\ or current_user.is_administrator: db.session.delete(comment)",
"= form.title.data # TODO: delete if article.name is None: article.name = form.title.data article.body",
"user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment',",
"article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author \\ and not",
"return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name",
"methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user",
"build_index, rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() #",
"redirect, url_for, request, abort from flask_login import current_user, login_required from app import db,",
"redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author",
"article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id):",
"db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title):",
"更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def comment():",
"render_template, redirect, url_for, request, abort from flask_login import current_user, login_required from app import",
"current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError: current_user_rating = None try: current_user_id = current_user.id except",
"permission_required, author_required from app.article import article as article_blueprint from app.article.forms import EditArticleForm, ModifyArticleForm",
"in article.tags) form.body.data = article.body return render_template('article/edit.html', form=form) @article_blueprint.route('/rating', methods=['POST']) @login_required def rating():",
"!= article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data #",
"current_user, login_required from app import db, redis from app.models import Article, Comment, Permission,",
"Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article)",
"article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else:",
"form = ModifyArticleForm(article=article) if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if",
"except AttributeError: current_user_rating = None try: current_user_id = current_user.id except AttributeError: current_user_id =",
"rebuild_index @article_blueprint.route('/<title>', methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章",
"rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建 rating = Rating(value=rating_value,",
"avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating = None",
"EditArticleForm() if form.validate_on_submit(): article = Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object()",
"def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating =",
"= Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建 rating = Rating(value=rating_value, user_id=user_id,",
"return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user !=",
"form.tags.data = \" \".join(tag.name for tag in article.tags) form.body.data = article.body return render_template('article/edit.html',",
"= ModifyArticleForm(article=article) if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit():",
"@article_blueprint.route('/modify/<title>', methods=['GET', 'POST']) @author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if",
"if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title =",
"= None try: current_user_id = current_user.id except AttributeError: current_user_id = None return render_template('article/article.html',",
"if comment.article.author == current_user\\ or comment.author == current_user\\ or current_user.is_administrator: db.session.delete(comment) flash('评论已经删除') return",
"def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title,",
"article.category.id form.tags.data = \" \".join(tag.name for tag in article.tags) form.body.data = article.body return",
"redis from app.models import Article, Comment, Permission, Rating from app.decorators import permission_required, author_required",
"@permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author ==",
"None try: current_user_id = current_user.id except AttributeError: current_user_id = None return render_template('article/article.html', article=article,",
"methods=['GET']) def article(title): \"\"\" 显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles =",
"and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username))) @article_blueprint.route('/modify/<title>', methods=['GET',",
"db, redis from app.models import Article, Comment, Permission, Rating from app.decorators import permission_required,",
"request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment)",
"if article.name is None: article.name = form.title.data article.body = form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split('",
"ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings))",
"article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO:",
"current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) if form.validate_on_submit(): article.title = form.title.data",
"db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id",
"= Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER):",
"= form.body.data article.set_category(form.category.data) article.delete_tags() article.add_tags(form.tags.data.split(' ')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title))",
"AttributeError: current_user_rating = None try: current_user_id = current_user.id except AttributeError: current_user_id = None",
"article = Article( title=form.title.data, # TODO: delete name=form.title.data, body=form.body.data, author=current_user._get_current_object() ) article.set_category(form.category.data) article.add_tags(form.tags.data.strip().split('",
"delete(title): article = Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403)",
"@author_required def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author",
"flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data = \"",
"sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating",
"= None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET',",
"else: # 更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required",
"return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404()",
"article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete()) return (redirect(request.args.get('next') or url_for('user.user', username=current_user.username)))",
"moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\ or comment.author == current_user\\ or",
"article.title = form.title.data # TODO: delete if article.name is None: article.name = form.title.data",
"= article.category.id form.tags.data = \" \".join(tag.name for tag in article.tags) form.body.data = article.body",
"article_id=article_id).first() if rating is None: # 新建 rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else:",
"')) db.session.add(article) db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data =",
"withscores=True) # 获取评分情况 ratings = article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda",
"try: current_user_id = current_user.id except AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles,",
"= Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True) # 获取评分情况 ratings",
"redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required def delete(title): article = Article.query.filter_by(title=title).first_or_404() if",
"article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name for tag in article.tags) form.body.data",
"comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required",
"rating = Rating(value=rating_value, user_id=user_id, article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating) return",
"@login_required def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating",
"article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form = EditArticleForm() if form.validate_on_submit():",
"url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>') @login_required @permission_required(Permission.MODERATE_COMMENTS) def moderate(comment_id): comment = Comment.query.get_or_404(comment_id) if comment.article.author == current_user\\",
"import flash, render_template, redirect, url_for, request, abort from flask_login import current_user, login_required from",
"form.validate_on_submit(): article.title = form.title.data # TODO: delete if article.name is None: article.name =",
"rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data =",
"@article_blueprint.route('/rating', methods=['POST']) @login_required def rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id =",
"flask import flash, render_template, redirect, url_for, request, abort from flask_login import current_user, login_required",
"db.session.commit() rebuild_index.delay(article.id) flash('您的文章已经成功修改') return redirect(url_for('article.article', title=article.title)) form.title.data = article.title form.category.data = article.category.id form.tags.data",
"显示单篇文章 \"\"\" article = Article.query.filter_by(title=title).first_or_404() # 相似文章 sim_articles = redis.zrevrange(article.title, 0, 4, withscores=True)",
"article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating",
"abort(403) if form.validate_on_submit(): article.title = form.title.data # TODO: delete if article.name is None:",
"comment(): user_id = request.form['user_id'] article_id = request.form['article_id'] comment_body = request.form['comment_body'] comment = Comment(body=comment_body,",
"form.title.data = article.title form.category.data = article.category.id form.tags.data = \" \".join(tag.name for tag in",
"rating(): user_id = request.json['user_id'] rating_value = request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id,",
"= article.ratings.all() num_rating = len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings)) /",
"num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id) @article_blueprint.route('/edit', methods=['GET', 'POST']) @author_required def edit(): form =",
"request.form['comment_body'] comment = Comment(body=comment_body, article_id=article_id, author_id=user_id) db.session.add(comment) flash(\"你的评论已提交\") return redirect(request.args.get('next') or url_for('main.index')) @article_blueprint.route('/moderate/<comment_id>')",
"from flask_login import current_user, login_required from app import db, redis from app.models import",
"def modify(title): article = Article.query.filter_by(title=title).first_or_404() form = ModifyArticleForm(article=article) if current_user != article.author \\",
"= request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None: # 新建 rating",
"AttributeError: current_user_id = None return render_template('article/article.html', article=article, sim_articles=sim_articles, num_rating=num_rating, avg_rating=avg_rating, current_user_rating=current_user_rating, article_id=article.id, user_id=current_user_id)",
"= request.json['rating_value'] article_id = request.json['article_id'] rating = Rating.query.filter_by(user_id=user_id, article_id=article_id).first() if rating is None:",
"/ num_rating except ZeroDivisionError: avg_rating = None try: current_user_rating = article.ratings.filter_by(user=current_user).first().value except AttributeError:",
"article_id=article_id) else: # 更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST'])",
"article.add_tags(form.tags.data.strip().split(' ')) db.session.add(article) db.session.commit() build_index.delay(article.id) return redirect(url_for('article.article', title=article.title)) return render_template('article/edit.html', form=form) @article_blueprint.route('/delete/<title>') @author_required",
"# 更改 rating.value = rating_value db.session.add(rating) return \"Rating done.\" @article_blueprint.route('/comment', methods=['POST']) @login_required def",
"from app.decorators import permission_required, author_required from app.article import article as article_blueprint from app.article.forms",
"= len(ratings) try: avg_rating = sum(map(lambda rating: rating.value, ratings)) / num_rating except ZeroDivisionError:",
"= Article.query.filter_by(title=title).first_or_404() if current_user != article.author \\ and not current_user.can(Permission.ADMINISTER): abort(403) else: flash(article.delete())"
] |
[
"import core, tools from .config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name,",
"exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth, followlinks=followlinks, include=include, exclude=exclude, mode=mode, safe_walk=safe_walk)",
"path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth, followlinks=followlinks,",
"main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth,",
"core, tools from .config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build)",
".config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path,",
"def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True,",
"build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None,",
"Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist',",
"def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path,",
"class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None,",
"super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return",
"include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth, followlinks=followlinks, include=include, exclude=exclude, mode=mode,",
"max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth, followlinks=followlinks, include=include,",
"followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list( path, max_depth=max_depth, followlinks=followlinks, include=include, exclude=exclude,",
"import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0,",
"from .config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self,",
"catstuff import core, tools from .config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self):",
"build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs): return tools.path.import_file_list(",
"mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False,",
"from catstuff import core, tools from .config import mod_name, build class Filelist(core.plugins.CSTask): def",
"__init__(self): super().__init__(mod_name, build) def main(self, path, max_depth=0, followlinks=False, include=None, exclude=None, mode='whitelist', safe_walk=True, **kwargs):",
"tools from .config import mod_name, build class Filelist(core.plugins.CSTask): def __init__(self): super().__init__(mod_name, build) def"
] |
[] |
[] |
[
"= AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\":",
"gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key,",
"e = APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e",
"use_code(self, key, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"promo\",",
"= StoreAPI() profile = ProfileAPI() social = SocialAPI() message = MessageAPI() promo =",
"self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None,",
"gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code, e.body) return profile @promise",
"class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str):",
"\"config:\" + str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key) if cached: return",
"component, env=None, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\",",
"await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code,",
"*ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"]",
"e: raise APIError(e.code, e.body) try: result = result[\"result\"] except KeyError: raise APIError(500, \"Response",
"\"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body)",
"if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be a",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as e: raise",
"merge=True, handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should be a",
"as e: raise APIError(e.code, e.body) return account_id @promise async def release_name(self, kind, handler=None,",
"Internal() try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except",
"= APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else:",
"# noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name =",
"= ConfigAPI() store = StoreAPI() profile = ProfileAPI() social = SocialAPI() message =",
"APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await",
"a string\") key = \"profile:\" + str(path) if not profile: profile = {}",
"= SocialAPI() message = MessageAPI() promo = PromoAPI() web = WebAPI() event =",
"handler.get_cache(key) if cached: return cached internal = Internal() try: config = await internal.request(",
"= handler.get_cache(key) if cached: return cached internal = Internal() try: info = await",
"APIError(e.code, e.body) return events class APIS(object): config = ConfigAPI() store = StoreAPI() profile",
"\"store:\" + str(name) cached = handler.get_cache(key) if cached: return cached internal = Internal()",
"\"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code, e.body) return",
"*args, **kwargs): application = Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\":",
"app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\"",
"e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async def new_order(self, store,",
"e.body) handler.set_cache(key, config) return config @promise async def new_order(self, store, item, currency, amount,",
"amount=amount, component=component, env=env) except InternalError as e: raise APIError(e.code, e.body) return result @promise",
"if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a JSON object\") internal",
"result = result[\"result\"] except KeyError: raise APIError(500, \"Response had no 'result' field.\") return",
"try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as",
"def release_name(self, kind, handler=None, *ignored): internal = Internal() try: released = await internal.request(",
"API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay)",
"PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None,",
"*ignored): internal = Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages,",
"= [] self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request) except HTTPError as",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code, e.body) return released @promise",
"def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal = Internal() try: await internal.request(",
"return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key, handler=None,",
"InternalError as e: raise APIError(e.code, e.body) return events class APIS(object): config = ConfigAPI()",
"kind, handler=None, *ignored): internal = Internal() try: released = await internal.request( \"social\", \"release_name\",",
"\"Response had no 'result' field.\") return result class EventAPI(object): @promise async def update_event_profile(self,",
"profile = {} internal = Internal() try: profile = await internal.request( \"profile\", \"update_profile\",",
"e.body) return released @promise async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored):",
"profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not",
"PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None, *ignored): internal =",
"Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except",
"async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher =",
"env=env) except InternalError as e: raise APIError(e.code, e.body) return result @promise async def",
"Future() existing_futures.append(future) result = await future return result new_futures = [] self.rc_cache[url] =",
"@promise async def release_name(self, kind, handler=None, *ignored): internal = Internal() try: released =",
"account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code, e.body) return released @promise async",
"update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path and not isinstance(path, (list,",
"InternalError as e: raise APIError(e.code, e.body) return result @promise async def update_order(self, order_id,",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return events @promise async",
"Internal() try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except",
"Internal() try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except",
"future = Future() existing_futures.append(future) result = await future return result new_futures = []",
"APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event",
"headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if",
"\"Path should be a list/tuple\") internal = Internal() try: profile = await internal.request(",
"raise APIError(e.code, e.body) try: result = result[\"result\"] except KeyError: raise APIError(500, \"Response had",
"update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal = Internal() try: events = await",
"account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return profile @promise",
"update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path",
"\"Path should be a string\") internal = Internal() try: profile = await internal.request(",
"noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored): internal =",
"be a string\") internal = Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\",",
"raise APIError(e.code, e.body) return released @promise async def update_profile(self, group_id, profile=None, path=None, merge=True,",
"APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async def query(self, query, limit=1000, handler=None,",
"a JSON object\") internal = Internal() try: results = await internal.request( \"profile\", \"query_profiles\",",
"events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError",
"= await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e:",
"*ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name) +",
"\"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key,",
"e.body) return account_id @promise async def release_name(self, kind, handler=None, *ignored): internal = Internal()",
"e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal class StoreAPI(object):",
"path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should be",
"\"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError as",
"or [], merge=merge, synced=synced) except InternalError as e: raise APIError(e.code, e.body) return profile",
"handler.set_cache(key, config) return config @promise async def new_order(self, store, item, currency, amount, component,",
"sender, messages, authoritative=True, handler=None, *ignored): internal = Internal() try: await internal.request( \"message\", \"send_batch\",",
"isinstance(path, (list, tuple)): raise APIError(400, \"Path should be a list/tuple\") internal = Internal()",
"if existing_futures is not None: future = Future() existing_futures.append(future) result = await future",
"*ignored): if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be",
"def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher = await",
"InternalError from anthill.common.validate import validate_value from anthill.common.server import Server from . util import",
"tornado.gen.moment def log(message): handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async",
"await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError",
"noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise",
"from anthill.common.server import Server from . util import promise, PromiseContext, APIError API_TIMEOUT =",
"result = await future return result new_futures = [] self.rc_cache[url] = new_futures try:",
"result new_futures = [] self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request) except",
"try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError",
"\"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e: raise",
"import validate_value from anthill.common.server import Server from . util import promise, PromiseContext, APIError",
"for future in new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal class",
"e: raise APIError(e.code, e.body) return result @promise async def update_order(self, order_id, handler=None, *ignored):",
"try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"return profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if",
"path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles",
"import promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async def",
"dict): raise APIError(400, \"Group profiles should be a dict\") if path and not",
"internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise",
"PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async",
"HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as _opts from",
"as e: e = APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url]",
"else: body = response.body for future in new_futures: future.set_result(body) del self.rc_cache[url] return body",
"@promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles,",
"name, handler=None, *ignored): if not isinstance(name, str): raise APIError(400, \"name should be a",
"e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key,",
"\"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e: raise",
"= Internal() try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile,",
"async def acquire_name(self, kind, name, handler=None, *ignored): internal = Internal() try: profile =",
"\"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code, e.body) try:",
"had no 'result' field.\") return result class EventAPI(object): @promise async def update_event_profile(self, event_id,",
"= await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except",
"\"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return",
"future.set_exception(e) del self.rc_cache[url] raise e else: body = response.body for future in new_futures:",
"\"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\":",
"future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async def",
"a list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT,",
"SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None, *ignored): internal = Internal() try:",
"@promise async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal = Internal() try:",
"be a string\") key = \"store:\" + str(name) cached = handler.get_cache(key) if cached:",
"*ignored): internal = Internal() try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind,",
"**kwargs): application = Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"],",
"a dict\") if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should",
"(list, tuple)): raise APIError(400, \"Path should be a list/tuple\") internal = Internal() try:",
"internal = Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative)",
"as _opts from anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server",
"APIError(400, \"Path should be a string\") key = \"profile:\" + str(path) if not",
"as e: raise APIError(e.code, e.body) return profile @promise async def check_name(self, kind, name,",
"PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored): internal = Internal() try: result",
"\"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code,",
"= await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body) return",
"self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request) except HTTPError as e: e",
"APIS(object): config = ConfigAPI() store = StoreAPI() profile = ProfileAPI() social = SocialAPI()",
"as readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob, name, {'value': callback, 'writable':",
"not None: future = Future() existing_futures.append(future) result = await future return result new_futures",
"= Internal() try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store,",
"list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"= self.rc_cache.get(url, None) if existing_futures is not None: future = Future() existing_futures.append(future) result",
"handler=None, *ignored): internal = Internal() try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"],",
"await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) #",
"internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code,",
"account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code, e.body) try: result = result[\"result\"]",
"query=query, limit=limit) except InternalError as e: raise APIError(e.code, e.body) return results # noinspection",
"url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None)",
"noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise",
"= await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise",
"= await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e:",
"body = response.body for future in new_futures: future.set_result(body) del self.rc_cache[url] return body #",
"e.body) return profile @promise async def check_name(self, kind, name, handler=None, *ignored): internal =",
"class PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored): internal = Internal() try:",
"handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name)",
"sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social,",
"handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be a",
"expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config,",
"gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\",",
"InternalError as e: raise APIError(e.code, e.body) return result @promise async def update_orders(self, handler=None,",
"result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e:",
"sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment",
"await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code,",
"internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body)",
"gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) return",
"def expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\":",
"APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({",
"update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400,",
"profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except",
"[], merge=merge, synced=synced) except InternalError as e: raise APIError(e.code, e.body) return profile #",
"{} internal = Internal() try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"],",
"from anthill.common.validate import validate_value from anthill.common.server import Server from . util import promise,",
"not isinstance(name, str): raise APIError(400, \"name should be a string\") key = \"store:\"",
"path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be a list/tuple\")",
"\"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body)",
"query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should",
"gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return account_id @promise",
"release_name(self, kind, handler=None, *ignored): internal = Internal() try: released = await internal.request( \"social\",",
"= Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except",
"# noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self, name, handler=None, *ignored): if",
"= Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path",
"return results # noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind, name,",
"as e: raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise",
"except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def update_group_profiles(self,",
"async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key =",
"profile, path=None, merge=True, handler=None): internal = Internal() try: events = await internal.request( \"event\",",
"raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async def new_order(self, store, item,",
"moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message,",
"@promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events =",
"handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs):",
"be a JSON object\") internal = Internal() try: results = await internal.request( \"profile\",",
"get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" +",
"try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError",
"@promise async def acquire_name(self, kind, name, handler=None, *ignored): internal = Internal() try: profile",
"\"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code, e.body)",
"def new_order(self, store, item, currency, amount, component, env=None, handler=None, *ignored): internal = Internal()",
"kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return account_id @promise async",
"_opts from anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server import",
"except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async",
"async def update_order(self, order_id, handler=None, *ignored): internal = Internal() try: result = await",
"profile=None, path=None, merge=True, handler=None, *ignored): if path and not isinstance(path, (list, tuple)): raise",
"def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\"",
"handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a JSON",
"internal = Internal() try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"handler=None, *ignored): if not isinstance(name, str): raise APIError(400, \"name should be a string\")",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return",
"raise e else: body = response.body for future in new_futures: future.set_result(body) del self.rc_cache[url]",
"as e: raise APIError(e.code, e.body) return events class APIS(object): config = ConfigAPI() store",
"events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"])",
"\"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\":",
"Internal() try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError",
"*ignored): internal = Internal() try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise",
"store = StoreAPI() profile = ProfileAPI() social = SocialAPI() message = MessageAPI() promo",
"*ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be a dict\")",
"\"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code, e.body) return released",
"from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as _opts from anthill.common.internal import",
"@promise async def new_order(self, store, item, currency, amount, component, env=None, handler=None, *ignored): internal",
"results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as",
"\"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\":",
"e.body) return result @promise async def update_orders(self, handler=None, *ignored): internal = Internal() try:",
"key = \"profile:\" + str(path) if not profile: profile = {} internal =",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code, e.body) try: result =",
"internal = Internal() try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name)",
"noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored): if not",
"be a list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profile\",",
"query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be",
"# noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None, *ignored):",
"@promise async def check_name(self, kind, name, handler=None, *ignored): internal = Internal() try: account_id",
"\"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code,",
"e: raise APIError(e.code, e.body) return profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True,",
"internal = Internal() try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code, e.body) return result @promise",
"result @promise async def update_orders(self, handler=None, *ignored): internal = Internal() try: result =",
"e.body) return events class APIS(object): config = ConfigAPI() store = StoreAPI() profile =",
"= 5 # noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) #",
"raise APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal class StoreAPI(object): @promise",
"self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code, e.message) for future in new_futures:",
"handler.set_cache(key, profile) return profile @promise async def query(self, query, limit=1000, handler=None, *ignored): if",
"APIError(e.code, e.body) return results # noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self,",
"*ignored): if not isinstance(name, str): raise APIError(400, \"name should be a string\") key",
"# noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {}",
"profile=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) return profile @promise",
"handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts,",
"APIError(e.code, e.body) return profile @promise async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored):",
"APIS.admin }) # define them as readonly for name, callback in expose_objects.items(): context.Object.defineProperty(",
"5 # noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection",
"*ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"@promise async def query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise",
"return result @promise async def update_orders(self, handler=None, *ignored): internal = Internal() try: result",
"not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a JSON object\") internal =",
"Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError",
"if cached: return cached internal = Internal() try: info = await internal.request( \"config\",",
"\"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise APIError(e.code, e.body) return",
"= Internal() try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time,",
"internal = Internal() try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"except InternalError as e: raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class",
"PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal",
"async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None):",
"await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise",
"path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return",
"+ str(name) cached = handler.get_cache(key) if cached: return cached internal = Internal() try:",
"InternalError as e: raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object):",
"= await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as",
"def update_order(self, order_id, handler=None, *ignored): internal = Internal() try: result = await internal.request(",
"PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async def sleep(delay, handler=None):",
"handler=None, *ignored): internal = Internal() try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"],",
"+ str(app_version) cached = handler.get_cache(key) if cached: return cached internal = Internal() try:",
"ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"]",
"= \"config:\" + str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key) if cached:",
"application = Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\":",
"\"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\":",
"} if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them as readonly for",
"import tornado.gen from tornado.gen import sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from",
"merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return events",
"str(app_version) cached = handler.get_cache(key) if cached: return cached internal = Internal() try: info",
"if not isinstance(path, str): raise APIError(400, \"Path should be a string\") internal =",
"# noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored): internal",
"str): raise APIError(400, \"Path should be a string\") key = \"profile:\" + str(path)",
"APIError(e.code, e.body) try: result = result[\"result\"] except KeyError: raise APIError(500, \"Response had no",
"JSON object\") internal = Internal() try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT,",
"}) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache =",
"profile = ProfileAPI() social = SocialAPI() message = MessageAPI() promo = PromoAPI() web",
"\"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event }",
"Server from . util import promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection",
"= Internal() try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"])",
"async def get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path",
"+ str(path) if not profile: profile = {} internal = Internal() try: profile",
"{ \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store,",
"except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection",
"APIError(e.code, e.body) return result @promise async def update_order(self, order_id, handler=None, *ignored): internal =",
"PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored): if not isinstance(path,",
"# noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def log(message): handler =",
"moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object):",
"e: raise APIError(e.code, e.body) return events class APIS(object): config = ConfigAPI() store =",
"APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body",
"group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) return profile",
"@promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher",
"internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise APIError(e.code,",
"get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url,",
"kind, name, handler=None, *ignored): internal = Internal() try: account_id = await internal.request( \"social\",",
"internal = Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"],",
"group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path and not isinstance(path, (list, tuple)):",
"except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async",
"not isinstance(path, str): raise APIError(400, \"Path should be a string\") key = \"profile:\"",
"not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be a dict\") if path",
"field.\") return result class EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None, merge=True,",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body) return events",
"del self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self,",
"should be a string\") key = \"profile:\" + str(path) if not profile: profile",
"kind, name, handler=None, *ignored): internal = Internal() try: profile = await internal.request( \"social\",",
"= {} @promise async def get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url,",
"\"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def",
"anthill.common.server import Server from . util import promise, PromiseContext, APIError API_TIMEOUT = 5",
"order_id=order_id) except InternalError as e: raise APIError(e.code, e.body) return result @promise async def",
"Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\":",
"PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version",
"\"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code,",
"raise APIError(400, \"Path should be a string\") key = \"profile:\" + str(path) if",
"import SimpleAsyncHTTPClient from .. import options as _opts from anthill.common.internal import Internal, InternalError",
"except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def check_name(self,",
"except InternalError as e: raise APIError(e.code, e.body) return result @promise async def update_orders(self,",
"limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a",
"import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as _opts",
"e: raise APIError(e.code, e.body) return released @promise async def update_profile(self, group_id, profile=None, path=None,",
"APIError(400, \"Path should be a string\") internal = Internal() try: profile = await",
"try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError",
"InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal",
"internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError",
"new_futures = [] self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request) except HTTPError",
"item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as e: raise APIError(e.code, e.body) return",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return events @promise",
"handler.set_cache(key, info) return info # noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self,",
"self.rc_cache.get(url, None) if existing_futures is not None: future = Future() existing_futures.append(future) result =",
"isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be a dict\") if path and",
"async def get(self, name, handler=None, *ignored): if not isinstance(name, str): raise APIError(400, \"name",
"import Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server import Server from .",
"get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should be",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError as e: raise",
"APIError(e.code, e.body) return result @promise async def update_orders(self, handler=None, *ignored): internal = Internal()",
"expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web,",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code, e.body) return result",
"def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path and not isinstance(path,",
"account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile)",
"not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be a list/tuple\") internal =",
"internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as",
"name=name) except InternalError as e: raise APIError(e.code, e.body) return account_id @promise async def",
"application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection",
"\"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client",
"config @promise async def new_order(self, store, item, currency, amount, component, env=None, handler=None, *ignored):",
"\"Group profiles should be a dict\") if path and not isinstance(path, (list, tuple)):",
"def check_name(self, kind, name, handler=None, *ignored): internal = Internal() try: account_id = await",
"expose_objects.update({ \"admin\": APIS.admin }) # define them as readonly for name, callback in",
"self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self, url, headers=None, *args,",
"= ProfileAPI() social = SocialAPI() message = MessageAPI() promo = PromoAPI() web =",
"raise APIError(e.code, e.body) return events class APIS(object): config = ConfigAPI() store = StoreAPI()",
"MessageAPI() promo = PromoAPI() web = WebAPI() event = EventAPI() admin = AdminAPI()",
"async def get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures",
"@promise async def update_orders(self, handler=None, *ignored): internal = Internal() try: result = await",
"WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self,",
"class SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None, *ignored): internal = Internal()",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body) return",
"tornado.gen import sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient",
"e: raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async",
"raise APIError(400, \"Path should be a list/tuple\") internal = Internal() try: profile =",
"except InternalError as e: raise APIError(e.code, e.body) try: result = result[\"result\"] except KeyError:",
"e: raise APIError(e.code, e.body) return profile @promise async def check_name(self, kind, name, handler=None,",
"PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored): internal = Internal()",
"import Server from . util import promise, PromiseContext, APIError API_TIMEOUT = 5 #",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return result #",
"key = \"store:\" + str(name) cached = handler.get_cache(key) if cached: return cached internal",
"class ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version =",
"events class APIS(object): config = ConfigAPI() store = StoreAPI() profile = ProfileAPI() social",
"import options as _opts from anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value",
"\"Query should be a JSON object\") internal = Internal() try: results = await",
"\"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return",
"handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT,",
"InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async def",
"web = WebAPI() event = EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects",
"await future return result new_futures = [] self.rc_cache[url] = new_futures try: response =",
"PromoAPI() web = WebAPI() event = EventAPI() admin = AdminAPI() def expose(context, is_server=False):",
"return profile @promise async def query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query,",
"async def check_name(self, kind, name, handler=None, *ignored): internal = Internal() try: account_id =",
"promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async def sleep(delay,",
"request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is not",
"a list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT,",
"await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except",
"handler=None, *args, **kwargs): application = Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", {",
"APIError(e.code, e.body) return account_id @promise async def release_name(self, kind, handler=None, *ignored): internal =",
"= await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced)",
"timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body)",
"released @promise async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path",
"handler=None, *ignored): if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should",
"await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise",
"account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return events @promise async def",
"@promise async def get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers)",
"# noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored): if",
"path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile",
"@promise async def use_code(self, key, handler=None, *ignored): internal = Internal() try: result =",
"e else: body = response.body for future in new_futures: future.set_result(body) del self.rc_cache[url] return",
"async def use_code(self, key, handler=None, *ignored): internal = Internal() try: result = await",
"def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str): raise APIError(400,",
"send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal = Internal() try: await internal.request( \"message\",",
"\"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin })",
"raise APIError(400, \"name should be a string\") key = \"store:\" + str(name) cached",
"internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id,",
"be a dict\") if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path",
"from . util import promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal",
"as e: raise APIError(e.code, e.body) return released @promise async def update_profile(self, group_id, profile=None,",
"delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher = await application.acquire_publisher()",
"a string\") internal = Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT,",
"\"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code, e.body)",
"synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be",
"class EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal =",
"APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin }) #",
"gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body) return \"OK\"",
"is not None: future = Future() existing_futures.append(future) result = await future return result",
"app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return",
"def acquire_name(self, kind, name, handler=None, *ignored): internal = Internal() try: profile = await",
"# noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True, handler=None,",
"EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\":",
"list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"= await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e:",
"raise APIError(e.code, e.body) return events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal",
"def update_orders(self, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\",",
"except InternalError as e: raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal class",
"events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events",
"if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them as readonly for name,",
"isinstance(path, str): raise APIError(400, \"Path should be a string\") key = \"profile:\" +",
"APIError(e.code, e.body) return profile @promise async def check_name(self, kind, name, handler=None, *ignored): internal",
"@promise async def get(self, handler=None, *ignored): app_name = handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key",
"Internal() try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError",
"await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env)",
"@promise async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal = Internal() try:",
"e.body) return result @promise async def update_order(self, order_id, handler=None, *ignored): internal = Internal()",
"use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is not None: future =",
"except InternalError as e: raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal class",
"internal = Internal() try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name)",
"not profile: profile = {} internal = Internal() try: profile = await internal.request(",
"e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender,",
"raise APIError(e.code, e.body) return account_id @promise async def release_name(self, kind, handler=None, *ignored): internal",
"{} @promise async def get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True,",
"= handler.get_cache(key) if cached: return cached internal = Internal() try: config = await",
"profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge,",
"validate_value from anthill.common.server import Server from . util import promise, PromiseContext, APIError API_TIMEOUT",
"handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application",
"event_id, profile, path=None, merge=True, handler=None): internal = Internal() try: events = await internal.request(",
"\"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key,",
"handler.get_cache(key) if cached: return cached internal = Internal() try: info = await internal.request(",
"path=None, merge=True, handler=None, *ignored): if path and not isinstance(path, (list, tuple)): raise APIError(400,",
"internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code,",
"internal = Internal() try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path,",
"except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def update(self,",
"return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender, messages,",
"async def query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400,",
"SimpleAsyncHTTPClient from .. import options as _opts from anthill.common.internal import Internal, InternalError from",
"APIError(e.code, e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self,",
"is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them as readonly for name, callback",
"@promise async def get(self, name, handler=None, *ignored): if not isinstance(name, str): raise APIError(400,",
"order_id, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_order\",",
"path=\"\", handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should be a",
"except HTTPError as e: e = APIError(e.code, e.message) for future in new_futures: future.set_exception(e)",
"get(self, name, handler=None, *ignored): if not isinstance(name, str): raise APIError(400, \"name should be",
"= { \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\":",
"list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events = await internal.request( \"event\",",
"tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def log(message): handler",
"e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal class StoreAPI(object): @promise async def",
"anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server import Server from",
"as e: raise APIError(e.code, e.body) return result @promise async def update_orders(self, handler=None, *ignored):",
"HTTPError as e: e = APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del",
"\"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return result",
"*ignored): internal = Internal() try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"handler=None, *ignored): internal = Internal() try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"],",
"merge=True, handler=None): internal = Internal() try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id,",
"internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except",
"async def new_order(self, store, item, currency, amount, component, env=None, handler=None, *ignored): internal =",
"name, handler=None, *ignored): internal = Internal() try: account_id = await internal.request( \"social\", \"check_name\",",
"name=name) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise",
"existing_futures is not None: future = Future() existing_futures.append(future) result = await future return",
"APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async def new_order(self, store, item, currency,",
"except InternalError as e: raise APIError(e.code, e.body) return account_id @promise async def release_name(self,",
"config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e:",
"handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT,",
"should be a dict\") if path and not isinstance(path, (list, tuple)): raise APIError(400,",
"async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal = Internal() try: events",
"= await self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code, e.message) for future",
"AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance()",
"= new_futures try: response = await self.http_client.fetch(request) except HTTPError as e: e =",
"APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them",
"EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal = Internal()",
"= await future return result new_futures = [] self.rc_cache[url] = new_futures try: response",
"sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from ..",
"= \"profile:\" + str(path) if not profile: profile = {} internal = Internal()",
"= await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError",
"path=path or [], merge=merge, synced=synced) except InternalError as e: raise APIError(e.code, e.body) return",
"APIError(500, \"Response had no 'result' field.\") return result class EventAPI(object): @promise async def",
"extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body) return events class APIS(object):",
"= EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\": log,",
"+ \":\" + str(app_version) cached = handler.get_cache(key) if cached: return cached internal =",
"from tornado.gen import sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import",
"try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except",
"except InternalError as e: raise APIError(e.code, e.body) return result @promise async def update_order(self,",
"gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError as e: raise APIError(e.code,",
"e.body) try: result = result[\"result\"] except KeyError: raise APIError(500, \"Response had no 'result'",
"if not isinstance(path, str): raise APIError(400, \"Path should be a string\") key =",
"\"name should be a string\") key = \"store:\" + str(name) cached = handler.get_cache(key)",
"= \"store:\" + str(name) cached = handler.get_cache(key) if cached: return cached internal =",
"validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a JSON object\") internal = Internal()",
"InternalError as e: raise APIError(e.code, e.body) return account_id @promise async def release_name(self, kind,",
"[] self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request) except HTTPError as e:",
"new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body = response.body for future in",
"as e: raise APIError(e.code, e.body) return events @promise async def list(self, extra_start_time=0, extra_end_time=0,",
"messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body) return \"OK\" # noinspection",
"await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def log(message):",
"def get(self, name, handler=None, *ignored): if not isinstance(name, str): raise APIError(400, \"name should",
"**kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is",
"async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path and not",
"del self.rc_cache[url] raise e else: body = response.body for future in new_futures: future.set_result(body)",
"= HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is not None:",
"APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal class StoreAPI(object): @promise async",
"cached = handler.get_cache(key) if cached: return cached internal = Internal() try: config =",
"*ignored): internal = Internal() try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"no 'result' field.\") return result class EventAPI(object): @promise async def update_event_profile(self, event_id, profile,",
"return cached internal = Internal() try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT,",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as e:",
"them as readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob, name, {'value': callback,",
"Internal() try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError",
"await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e:",
"handler=None): internal = Internal() try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile,",
"raise APIError(e.code, e.body) return result @promise async def update_orders(self, handler=None, *ignored): internal =",
"response.body for future in new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal",
"new_futures try: response = await self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code,",
"e.body) return profile @promise async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if",
"result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as",
"= result[\"result\"] except KeyError: raise APIError(500, \"Response had no 'result' field.\") return result",
"@promise async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str):",
"synced=synced) except InternalError as e: raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal",
"\"profile:\" + str(path) if not profile: profile = {} internal = Internal() try:",
"profile @promise async def check_name(self, kind, name, handler=None, *ignored): internal = Internal() try:",
"StoreAPI() profile = ProfileAPI() social = SocialAPI() message = MessageAPI() promo = PromoAPI()",
"if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should be a dict\") if",
"APIError(400, \"Query should be a JSON object\") internal = Internal() try: results =",
"object\") internal = Internal() try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"],",
"await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code,",
"e: raise APIError(e.code, e.body) return profile @promise async def update(self, profile=None, path=\"\", merge=True,",
"profiles should be a dict\") if path and not isinstance(path, (list, tuple)): raise",
"e: raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async",
"= SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self, url, headers=None, *args, **kwargs):",
"profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body)",
"internal = Internal() try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"],",
"extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events = await internal.request( \"event\", \"get_list\",",
"config) return config @promise async def new_order(self, store, item, currency, amount, component, env=None,",
"result[\"result\"] except KeyError: raise APIError(500, \"Response had no 'result' field.\") return result class",
"\"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError",
"accounts, gamespace_only=True, handler=None, *args, **kwargs): application = Server.instance() publisher = await application.acquire_publisher() await",
"internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e:",
"ProfileAPI() social = SocialAPI() message = MessageAPI() promo = PromoAPI() web = WebAPI()",
".. import options as _opts from anthill.common.internal import Internal, InternalError from anthill.common.validate import",
"HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as _opts from anthill.common.internal",
"APIError(400, \"Path should be a list/tuple\") internal = Internal() try: profile = await",
"account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e:",
"{ \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object):",
"def moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current if handler: handler.log(message) class",
"merge=merge, synced=synced) except InternalError as e: raise APIError(e.code, e.body) return profile # noinspection",
"*ignored): if not isinstance(path, str): raise APIError(400, \"Path should be a string\") key",
"handler=None): internal = Internal() try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal",
"APIError(e.code, e.body) return profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None,",
"internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code,",
"def get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should",
"e: raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async",
". util import promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise",
"currency=currency, amount=amount, component=component, env=env) except InternalError as e: raise APIError(e.code, e.body) return result",
"\"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code,",
"cached internal = Internal() try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"define them as readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob, name, {'value':",
"StoreAPI(object): @promise async def get(self, name, handler=None, *ignored): if not isinstance(name, str): raise",
"message = MessageAPI() promo = PromoAPI() web = WebAPI() event = EventAPI() admin",
"= Internal() try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except",
"key, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"promo\", \"use_code\",",
"account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body) return events class",
"anthill.common.validate import validate_value from anthill.common.server import Server from . util import promise, PromiseContext,",
"\":\" + str(app_version) cached = handler.get_cache(key) if cached: return cached internal = Internal()",
"log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile,",
"= Internal() try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile,",
"if not profile: profile = {} internal = Internal() try: profile = await",
"return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None,",
"try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as",
"as e: raise APIError(e.code, e.body) return result @promise async def update_order(self, order_id, handler=None,",
"try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge)",
"future in new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object):",
"profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as",
"gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config",
"APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self,",
"key=key) except InternalError as e: raise APIError(e.code, e.body) try: result = result[\"result\"] except",
"handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def",
"InternalError as e: raise APIError(e.code, e.body) return profile @promise async def update_group_profiles(self, group_profiles,",
"= Internal() try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key)",
"internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code, e.body)",
"string\") key = \"store:\" + str(name) cached = handler.get_cache(key) if cached: return cached",
"check_name(self, kind, name, handler=None, *ignored): internal = Internal() try: account_id = await internal.request(",
"def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal = Internal() try: events =",
"*args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures",
"from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options",
"profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as",
"profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True,",
"publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only",
"util import promise, PromiseContext, APIError API_TIMEOUT = 5 # noinspection PyUnusedLocal @promise async",
"\"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, config)",
"= await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e:",
"await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e:",
"handler=None, *ignored): internal = Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender,",
"APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them as readonly",
"gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache",
"isinstance(path, str): raise APIError(400, \"Path should be a string\") internal = Internal() try:",
"cached: return cached internal = Internal() try: config = await internal.request( \"store\", \"get_store\",",
"\"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return",
"kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async",
"merge=True, handler=None, *ignored): if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path",
"await self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code, e.message) for future in",
"= Future() existing_futures.append(future) result = await future return result new_futures = [] self.rc_cache[url]",
"= await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError",
"\"admin\": APIS.admin }) # define them as readonly for name, callback in expose_objects.items():",
"def query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query",
"APIError(400, \"name should be a string\") key = \"store:\" + str(name) cached =",
"APIError(e.code, e.body) return released @promise async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None,",
"path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async",
"merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group profiles should",
"profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except",
"amount, component, env=None, handler=None, *ignored): internal = Internal() try: result = await internal.request(",
"not isinstance(path, str): raise APIError(400, \"Path should be a string\") internal = Internal()",
"name, handler=None, *ignored): internal = Internal() try: profile = await internal.request( \"social\", \"acquire_name\",",
"tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as _opts from anthill.common.internal import Internal,",
"InternalError as e: raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal class SocialAPI(object):",
"from .. import options as _opts from anthill.common.internal import Internal, InternalError from anthill.common.validate",
"raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async def query(self, query, limit=1000,",
"internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body)",
"cached internal = Internal() try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name,",
"class APIS(object): config = ConfigAPI() store = StoreAPI() profile = ProfileAPI() social =",
"return result new_futures = [] self.rc_cache[url] = new_futures try: response = await self.http_client.fetch(request)",
"profile) return profile @promise async def query(self, query, limit=1000, handler=None, *ignored): if not",
"noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None, *ignored): internal",
"APIError(400, \"Group profiles should be a dict\") if path and not isinstance(path, (list,",
"str): raise APIError(400, \"Path should be a string\") internal = Internal() try: profile",
"raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal class SocialAPI(object): @promise async def",
"\"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise APIError(e.code, e.body)",
"try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge)",
"try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except InternalError as",
"self.rc_cache[url] raise e else: body = response.body for future in new_futures: future.set_result(body) del",
"profile @promise async def query(self, query, limit=1000, handler=None, *ignored): if not validate_value(query, \"json_dict\"):",
"timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code, e.body) return profile",
"\"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return account_id",
"future return result new_futures = [] self.rc_cache[url] = new_futures try: response = await",
"= handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\" +",
"InternalError as e: raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object):",
"return result class EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None):",
"HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is not None: future",
"kind=kind) except InternalError as e: raise APIError(e.code, e.body) return released @promise async def",
"None) if existing_futures is not None: future = Future() existing_futures.append(future) result = await",
"@promise async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if path and",
"event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code,",
"return events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try:",
"= WebAPI() event = EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects =",
"internal = Internal() try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"],",
"@promise async def moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current if handler:",
"future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body = response.body for",
"= Internal() try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit)",
"accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client =",
"group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError as e: raise APIError(e.code, e.body)",
"be a string\") key = \"profile:\" + str(path) if not profile: profile =",
"e: raise APIError(e.code, e.body) return account_id @promise async def release_name(self, kind, handler=None, *ignored):",
"profile @promise async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path,",
"update_order(self, order_id, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\",",
"extra_end_time=0, handler=None): internal = Internal() try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT,",
"__init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self, url, headers=None,",
"await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal",
"async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict):",
"return cached internal = Internal() try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT,",
"internal = Internal() try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind,",
"config = ConfigAPI() store = StoreAPI() profile = ProfileAPI() social = SocialAPI() message",
"async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str): raise",
"results # noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind, name, handler=None,",
"\"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as",
"return account_id @promise async def release_name(self, kind, handler=None, *ignored): internal = Internal() try:",
"dict\") if path and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be",
"= await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e:",
"PyUnusedLocal class StoreAPI(object): @promise async def get(self, name, handler=None, *ignored): if not isinstance(name,",
"should be a string\") key = \"store:\" + str(name) cached = handler.get_cache(key) if",
"SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self, url, headers=None, *args, **kwargs): request",
"account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code, e.body) return result @promise async",
"as e: raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal class SocialAPI(object): @promise",
"try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError",
"KeyError: raise APIError(500, \"Response had no 'result' field.\") return result class EventAPI(object): @promise",
"internal = Internal() try: info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version,",
"WebAPI() event = EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects = {",
"await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise",
"\"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server:",
"handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT,",
"PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current if",
"result class EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None, merge=True, handler=None): internal",
"internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise",
"store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as e: raise APIError(e.code, e.body)",
"result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored):",
"string\") key = \"profile:\" + str(path) if not profile: profile = {} internal",
"= response.body for future in new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection",
"store, item, currency, amount, component, env=None, handler=None, *ignored): internal = Internal() try: result",
"fields=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return",
"account_id @promise async def release_name(self, kind, handler=None, *ignored): internal = Internal() try: released",
"and not isinstance(path, (list, tuple)): raise APIError(400, \"Path should be a list/tuple\") internal",
"key = \"config:\" + str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key) if",
"\"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise",
"options as _opts from anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value from",
"timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info)",
"\"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code, e.body)",
"extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body) return events class APIS(object): config",
"Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server import Server from . util",
"existing_futures.append(future) result = await future return result new_futures = [] self.rc_cache[url] = new_futures",
"internal = Internal() try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"])",
"\"json_dict\"): raise APIError(400, \"Query should be a JSON object\") internal = Internal() try:",
"merge=merge) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def",
"cached = handler.get_cache(key) if cached: return cached internal = Internal() try: info =",
"tornado.gen from tornado.gen import sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient",
"try: result = result[\"result\"] except KeyError: raise APIError(500, \"Response had no 'result' field.\")",
"noinspection PyUnusedLocal @promise async def moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current",
"InternalError as e: raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object):",
"if handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args,",
"promo = PromoAPI() web = WebAPI() event = EventAPI() admin = AdminAPI() def",
"env=None, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"new_order\",",
"result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount,",
"Internal() try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path,",
"should be a JSON object\") internal = Internal() try: results = await internal.request(",
"e.body) handler.set_cache(key, profile) return profile @promise async def query(self, query, limit=1000, handler=None, *ignored):",
"@promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def",
"Internal() try: events = await internal.request( \"event\", \"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time)",
"\"Path should be a string\") key = \"profile:\" + str(path) if not profile:",
"str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key) if cached: return cached internal",
"admin = AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep,",
"new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async",
"return events class APIS(object): config = ConfigAPI() store = StoreAPI() profile = ProfileAPI()",
"AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\": moment,",
"log(message): handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self,",
"raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class MessageAPI(object): @promise async def",
"component=component, env=env) except InternalError as e: raise APIError(e.code, e.body) return result @promise async",
"for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body = response.body",
"authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal",
"as e: raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise",
"async def update_orders(self, handler=None, *ignored): internal = Internal() try: result = await internal.request(",
"str): raise APIError(400, \"name should be a string\") key = \"store:\" + str(name)",
"readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob, name, {'value': callback, 'writable': False})",
"InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async def",
"tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import options as",
"= Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path)",
"= await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError as e: raise APIError(e.code, e.body) try: result",
"return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None, *ignored):",
"await tornado.gen.moment def log(message): handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise",
"noinspection PyUnusedLocal class MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored):",
"as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info # noinspection PyUnusedLocal class",
"Internal() try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT,",
"try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [],",
"= await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only })",
"await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code,",
"# noinspection PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal",
"info) return info # noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self, name,",
"as e: raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise",
"return profile @promise async def update(self, profile=None, path=\"\", merge=True, handler=None, *ignored): if not",
"merge=merge) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise",
"raise APIError(e.code, e.body) return profile @promise async def check_name(self, kind, name, handler=None, *ignored):",
"def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events = await internal.request(",
"APIError(e.code, e.body) return events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal =",
"timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as e: raise APIError(e.code, e.body)",
"path=path) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def",
"@promise async def update_order(self, order_id, handler=None, *ignored): internal = Internal() try: result =",
"await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise",
"headers=headers) existing_futures = self.rc_cache.get(url, None) if existing_futures is not None: future = Future()",
"e: raise APIError(e.code, e.body) return result @promise async def update_orders(self, handler=None, *ignored): internal",
"internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code,",
"info = await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as",
"a string\") key = \"store:\" + str(name) cached = handler.get_cache(key) if cached: return",
"= handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\" + str(app_version) cached =",
"as e: raise APIError(e.code, e.body) try: result = result[\"result\"] except KeyError: raise APIError(500,",
"class MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal =",
"InternalError as e: raise APIError(e.code, e.body) return profile @promise async def update(self, profile=None,",
"from anthill.common.internal import Internal, InternalError from anthill.common.validate import validate_value from anthill.common.server import Server",
"publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class",
"account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async",
"\"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], path=path) except InternalError as e: raise APIError(e.code, e.body) return",
"internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as e:",
"cached: return cached internal = Internal() try: info = await internal.request( \"config\", \"get_configuration\",",
"messages, authoritative=True, handler=None, *ignored): internal = Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT,",
"try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError",
"def log(message): handler = PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async def",
"if not isinstance(name, str): raise APIError(400, \"name should be a string\") key =",
"str(path) if not profile: profile = {} internal = Internal() try: profile =",
"= Internal() try: result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id)",
"tuple)): raise APIError(400, \"Path should be a list/tuple\") internal = Internal() try: profile",
"as e: raise APIError(e.code, e.body) return profile @promise async def update_group_profiles(self, group_profiles, path=None,",
"authoritative=True, handler=None, *ignored): internal = Internal() try: await internal.request( \"message\", \"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"path=None, merge=True, handler=None): internal = Internal() try: events = await internal.request( \"event\", \"update_event_profile\",",
"return result @promise async def update_order(self, order_id, handler=None, *ignored): internal = Internal() try:",
"try: result = await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as",
"currency, amount, component, env=None, handler=None, *ignored): internal = Internal() try: result = await",
"e: raise APIError(e.code, e.body) return events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None):",
"timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise APIError(e.code, e.body) return results",
"= Internal() try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name)",
"\"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define them as",
"raise APIError(400, \"Path should be a string\") internal = Internal() try: profile =",
"as e: raise APIError(e.code, e.body) return profile @promise async def update(self, profile=None, path=\"\",",
"group_profiles, path=None, merge=True, synced=False, handler=None, *ignored): if not isinstance(group_profiles, dict): raise APIError(400, \"Group",
"raise APIError(500, \"Response had no 'result' field.\") return result class EventAPI(object): @promise async",
"class StoreAPI(object): @promise async def get(self, name, handler=None, *ignored): if not isinstance(name, str):",
"as e: raise APIError(e.code, e.body) handler.set_cache(key, config) return config @promise async def new_order(self,",
"ProfileAPI(object): @promise async def get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str): raise",
"try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except InternalError",
"@promise async def get(self, path=\"\", handler=None, *ignored): if not isinstance(path, str): raise APIError(400,",
"\"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin }) # define",
"Internal() try: profile = await internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except",
"Internal() try: profile = await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path,",
"def get(self, url, headers=None, *args, **kwargs): request = HTTPRequest(url=url, use_gzip=True, headers=headers) existing_futures =",
"result = await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise APIError(e.code, e.body) return result # noinspection",
"raise APIError(e.code, e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async def",
"= Internal() try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except",
"None: future = Future() existing_futures.append(future) result = await future return result new_futures =",
"return profile @promise async def check_name(self, kind, name, handler=None, *ignored): internal = Internal()",
"e.body) return profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False, handler=None, *ignored):",
"acquire_name(self, kind, name, handler=None, *ignored): internal = Internal() try: profile = await internal.request(",
"await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], account_id=handler.env[\"account\"], fields=profile, path=path, merge=merge) except InternalError as",
"e.body) return events @promise async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal()",
"self.rc_cache = {} @promise async def get(self, url, headers=None, *args, **kwargs): request =",
"gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info #",
"info # noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self, name, handler=None, *ignored):",
"InternalError as e: raise APIError(e.code, e.body) return released @promise async def update_profile(self, group_id,",
"await internal.request( \"social\", \"update_group_profile\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_id=group_id, profile=profile, path=path, merge=merge) except InternalError as",
"isinstance(name, str): raise APIError(400, \"name should be a string\") key = \"store:\" +",
"sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body) return \"OK\" #",
"except InternalError as e: raise APIError(e.code, e.body) return events class APIS(object): config =",
"Internal() try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item,",
"\"moment\": moment, \"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\":",
"raise APIError(e.code, e.body) return profile @promise async def update_group_profiles(self, group_profiles, path=None, merge=True, synced=False,",
"async def list(self, extra_start_time=0, extra_end_time=0, handler=None): internal = Internal() try: events = await",
"new_order(self, store, item, currency, amount, component, env=None, handler=None, *ignored): internal = Internal() try:",
"await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise",
"APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if is_server: expose_objects.update({ \"admin\": APIS.admin",
"existing_futures = self.rc_cache.get(url, None) if existing_futures is not None: future = Future() existing_futures.append(future)",
"e: e = APIError(e.code, e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise",
"\"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or [], merge=merge, synced=synced) except InternalError as e:",
"internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles,",
"MessageAPI(object): @promise async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal = Internal()",
"e.body) return result # noinspection PyUnusedLocal class ProfileAPI(object): @promise async def get(self, path=\"\",",
"name=name) except InternalError as e: raise APIError(e.code, e.body) return profile @promise async def",
"in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body = response.body for future",
"item, currency, amount, component, env=None, handler=None, *ignored): internal = Internal() try: result =",
"handler=None, *ignored): internal = Internal() try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT,",
"Internal() try: result = await internal.request( \"promo\", \"use_code\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], key=key) except",
"string\") internal = Internal() try: profile = await internal.request( \"profile\", \"get_my_profile\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"],",
"gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code, e.body) return profile",
"= Internal() try: config = await internal.request( \"store\", \"get_store\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], name=name) except",
"Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], group_profiles=group_profiles, path=path or",
"try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency,",
"return info # noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self, name, handler=None,",
"= Internal() try: events = await internal.request( \"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge,",
"\"get_list\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], extra_start_time=extra_start_time, extra_end_time=extra_end_time) except InternalError as e: raise APIError(e.code, e.body)",
"except InternalError as e: raise APIError(e.code, e.body) return profile # noinspection PyUnusedLocal class",
"= await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component,",
"# define them as readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob, name,",
"Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from .. import",
"= Internal() try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except",
"released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e:",
"raise APIError(e.code, e.body) return result @promise async def update_order(self, order_id, handler=None, *ignored): internal",
"*ignored): internal = Internal() try: result = await internal.request( \"store\", \"new_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"],",
"InternalError as e: raise APIError(e.code, e.body) return profile @promise async def check_name(self, kind,",
"APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo,",
"class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def",
"gamespace_id=handler.env[\"gamespace\"], query=query, limit=limit) except InternalError as e: raise APIError(e.code, e.body) return results #",
"try: response = await self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code, e.message)",
"internal.request( \"social\", \"acquire_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind, name=name) except InternalError as e: raise APIError(e.code,",
"class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True, handler=None, *args, **kwargs): application =",
"handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key)",
"app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\" + str(app_version) cached",
"internal = Internal() try: results = await internal.request( \"profile\", \"query_profiles\", timeout=API_TIMEOUT, gamespace_id=handler.env[\"gamespace\"], query=query,",
"return released @promise async def update_profile(self, group_id, profile=None, path=None, merge=True, handler=None, *ignored): if",
"InternalError as e: raise APIError(e.code, e.body) return events @promise async def list(self, extra_start_time=0,",
"limit=limit) except InternalError as e: raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal",
"= {} internal = Internal() try: profile = await internal.request( \"profile\", \"update_profile\", timeout=API_TIMEOUT,",
"if cached: return cached internal = Internal() try: config = await internal.request( \"store\",",
"be a list/tuple\") internal = Internal() try: profile = await internal.request( \"social\", \"update_group_profiles\",",
"APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self,",
"\"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async def use_code(self, key, handler=None, *ignored):",
"handler.env[\"application_name\"] app_version = handler.env[\"application_version\"] key = \"config:\" + str(app_name) + \":\" + str(app_version)",
"= PromiseContext.current if handler: handler.log(message) class AdminAPI(object): @promise async def delete_accounts(self, accounts, gamespace_only=True,",
"= Server.instance() publisher = await application.acquire_publisher() await publisher.publish(\"DEL\", { \"gamespace\": handler.env[\"gamespace\"], \"accounts\": accounts,",
"e: raise APIError(e.code, e.body) return results # noinspection PyUnusedLocal class SocialAPI(object): @promise async",
"def use_code(self, key, handler=None, *ignored): internal = Internal() try: result = await internal.request(",
"except KeyError: raise APIError(500, \"Response had no 'result' field.\") return result class EventAPI(object):",
"*ignored): if not isinstance(path, str): raise APIError(400, \"Path should be a string\") internal",
"profile: profile = {} internal = Internal() try: profile = await internal.request( \"profile\",",
"internal = Internal() try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind)",
"e.message) for future in new_futures: future.set_exception(e) del self.rc_cache[url] raise e else: body =",
"async def send_batch(self, sender, messages, authoritative=True, handler=None, *ignored): internal = Internal() try: await",
"raise APIError(e.code, e.body) return profile @promise async def update(self, profile=None, path=\"\", merge=True, handler=None,",
"raise APIError(400, \"Query should be a JSON object\") internal = Internal() try: results",
"e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async def query(self, query,",
"*ignored): if not validate_value(query, \"json_dict\"): raise APIError(400, \"Query should be a JSON object\")",
"response = await self.http_client.fetch(request) except HTTPError as e: e = APIError(e.code, e.message) for",
"\"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise APIError(e.code, e.body) return",
"import sleep, Future from tornado.httpclient import HTTPRequest, HTTPError from tornado.simple_httpclient import SimpleAsyncHTTPClient from",
"PyUnusedLocal @promise async def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async",
"except InternalError as e: raise APIError(e.code, e.body) return events @promise async def list(self,",
"ConfigAPI() store = StoreAPI() profile = ProfileAPI() social = SocialAPI() message = MessageAPI()",
"handler.env[\"gamespace\"], \"accounts\": accounts, \"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self):",
"raise APIError(400, \"Group profiles should be a dict\") if path and not isinstance(path,",
"+ str(app_name) + \":\" + str(app_version) cached = handler.get_cache(key) if cached: return cached",
"'result' field.\") return result class EventAPI(object): @promise async def update_event_profile(self, event_id, profile, path=None,",
"async def release_name(self, kind, handler=None, *ignored): internal = Internal() try: released = await",
"event = EventAPI() admin = AdminAPI() def expose(context, is_server=False): expose_objects = { \"log\":",
"SocialAPI() message = MessageAPI() promo = PromoAPI() web = WebAPI() event = EventAPI()",
"await internal.request( \"store\", \"update_order\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], order_id=order_id) except InternalError as e: raise",
"handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should be a string\")",
"\"web\": APIS.web, \"config\": APIS.config, \"store\": APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\":",
"update_orders(self, handler=None, *ignored): internal = Internal() try: result = await internal.request( \"store\", \"update_orders\",",
"is_server=False): expose_objects = { \"log\": log, \"sleep\": sleep, \"moment\": moment, \"web\": APIS.web, \"config\":",
"app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e: raise APIError(e.code, e.body) handler.set_cache(key, info) return info",
"try: released = await internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as",
"except InternalError as e: raise APIError(e.code, e.body) return released @promise async def update_profile(self,",
"should be a string\") internal = Internal() try: profile = await internal.request( \"profile\",",
"InternalError as e: raise APIError(e.code, e.body) try: result = result[\"result\"] except KeyError: raise",
"= PromoAPI() web = WebAPI() event = EventAPI() admin = AdminAPI() def expose(context,",
"}) # define them as readonly for name, callback in expose_objects.items(): context.Object.defineProperty( context.glob,",
"should be a list/tuple\") internal = Internal() try: profile = await internal.request( \"social\",",
"body # noinspection PyUnusedLocal class ConfigAPI(object): @promise async def get(self, handler=None, *ignored): app_name",
"= await internal.request( \"config\", \"get_configuration\", timeout=API_TIMEOUT, app_name=app_name, app_version=app_version, gamespace=handler.env[\"gamespace\"]) except InternalError as e:",
"social = SocialAPI() message = MessageAPI() promo = PromoAPI() web = WebAPI() event",
"noinspection PyUnusedLocal class StoreAPI(object): @promise async def get(self, name, handler=None, *ignored): if not",
"account=handler.env[\"account\"], store=store, item=item, currency=currency, amount=amount, component=component, env=env) except InternalError as e: raise APIError(e.code,",
"\"event\", \"update_event_profile\", event_id=event_id, profile=profile, path=path, merge=merge, timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e:",
"result @promise async def update_order(self, order_id, handler=None, *ignored): internal = Internal() try: result",
"async def moment(handler=None): await tornado.gen.moment def log(message): handler = PromiseContext.current if handler: handler.log(message)",
"\"gamespace_only\": gamespace_only }) # noinspection PyUnusedLocal class WebAPI(object): def __init__(self): self.http_client = SimpleAsyncHTTPClient()",
"def __init__(self): self.http_client = SimpleAsyncHTTPClient() self.rc_cache = {} @promise async def get(self, url,",
"def sleep(delay, handler=None): await tornado.gen.sleep(delay) # noinspection PyUnusedLocal @promise async def moment(handler=None): await",
"str(name) cached = handler.get_cache(key) if cached: return cached internal = Internal() try: config",
"profile=None, path=\"\", merge=True, handler=None, *ignored): if not isinstance(path, str): raise APIError(400, \"Path should",
"Internal() try: account_id = await internal.request( \"social\", \"check_name\", gamespace=handler.env[\"gamespace\"], kind=kind, name=name) except InternalError",
"raise APIError(e.code, e.body) return \"OK\" # noinspection PyUnusedLocal class PromoAPI(object): @promise async def",
"e.body) return results # noinspection PyUnusedLocal class SocialAPI(object): @promise async def acquire_name(self, kind,",
"\"send_batch\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], sender=sender, messages=messages, authoritative=authoritative) except InternalError as e: raise APIError(e.code, e.body)",
"= MessageAPI() promo = PromoAPI() web = WebAPI() event = EventAPI() admin =",
"APIS.store, \"profile\": APIS.profile, \"social\": APIS.social, \"message\": APIS.message, \"promo\": APIS.promo, \"event\": APIS.event } if",
"= await internal.request( \"store\", \"update_orders\", timeout=API_TIMEOUT, gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"]) except InternalError as e: raise",
"as e: raise APIError(e.code, e.body) handler.set_cache(key, profile) return profile @promise async def query(self,",
"internal.request( \"social\", \"release_name\", gamespace=handler.env[\"gamespace\"], account=handler.env[\"account\"], kind=kind) except InternalError as e: raise APIError(e.code, e.body)",
"in new_futures: future.set_result(body) del self.rc_cache[url] return body # noinspection PyUnusedLocal class ConfigAPI(object): @promise",
"return config @promise async def new_order(self, store, item, currency, amount, component, env=None, handler=None,"
] |
[
"['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except: print('mongo isn\\'t currently running...please",
"[], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [],",
"client.server_info() db = client.ast except: print('mongo isn\\'t currently running...please start it first') sys.exit()",
"[], \"dicts\": [], \"dictcomps\": [], \"functions\": [], } def output_json(handle): results = handle.find(",
"results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with open('results.json', 'a') as",
"currently running...please start it first') sys.exit() result_dict = { \"fors\": [], \"ifs\": [],",
"\"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [], } def output_json(handle): results =",
"\"dicts\": [], \"dictcomps\": [], \"functions\": [], } def output_json(handle): results = handle.find( {},",
"start it first') sys.exit() result_dict = { \"fors\": [], \"ifs\": [], \"lists\": [],",
"serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except: print('mongo isn\\'t currently running...please start",
"import json import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info()",
"= MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except: print('mongo isn\\'t",
"result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with open('results.json', 'a') as output_file:",
"{}, {'_id': False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists)",
"for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with",
"isn\\'t currently running...please start it first') sys.exit() result_dict = { \"fors\": [], \"ifs\":",
"[], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [], } def",
"} ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps)",
"[], \"dictcomps\": [], \"functions\": [], } def output_json(handle): results = handle.find( {}, {'_id':",
"output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with open('results.json', 'a') as output_file: output_file.write(json.dumps(result_dict))",
"output_json(handle): results = handle.find( {}, {'_id': False } ).limit(25) for result in results:",
"\"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\":",
"handle.find( {}, {'_id': False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs)",
"def output_json(handle): results = handle.find( {}, {'_id': False } ).limit(25) for result in",
"print('mongo isn\\'t currently running...please start it first') sys.exit() result_dict = { \"fors\": [],",
"\"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [], } def output_json(handle):",
"\"dictcomps\": [], \"functions\": [], } def output_json(handle): results = handle.find( {}, {'_id': False",
"= handle.find( {}, {'_id': False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors)",
"db = client.ast except: print('mongo isn\\'t currently running...please start it first') sys.exit() result_dict",
"\"functions\": [], } def output_json(handle): results = handle.find( {}, {'_id': False } ).limit(25)",
"result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with open('results.json',",
"= 2000) client.server_info() db = client.ast except: print('mongo isn\\'t currently running...please start it",
"False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts)",
"import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db =",
"first') sys.exit() result_dict = { \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [],",
"[], \"functions\": [], } def output_json(handle): results = handle.find( {}, {'_id': False }",
"result_dict = { \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [],",
"{'_id': False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps)",
"} def output_json(handle): results = handle.find( {}, {'_id': False } ).limit(25) for result",
"running...please start it first') sys.exit() result_dict = { \"fors\": [], \"ifs\": [], \"lists\":",
"= { \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\":",
"= client.ast except: print('mongo isn\\'t currently running...please start it first') sys.exit() result_dict =",
").limit(25) for result in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions)",
"[], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [], } def output_json(handle): results",
"client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except: print('mongo",
"sys.exit() result_dict = { \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\":",
"2000) client.server_info() db = client.ast except: print('mongo isn\\'t currently running...please start it first')",
"try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except:",
"results = handle.find( {}, {'_id': False } ).limit(25) for result in results: result_dict[result['type']].append(json.dumps(result))",
"pymongo import MongoClient import json import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS",
"import MongoClient import json import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS =",
"in results: result_dict[result['type']].append(json.dumps(result)) output_json(db.fors) output_json(db.ifs) output_json(db.lists) output_json(db.listcomps) output_json(db.dicts) output_json(db.dictcomps) output_json(db.functions) with open('results.json', 'a')",
"MongoClient import json import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000)",
"\"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [], \"functions\": [], }",
"from pymongo import MongoClient import json import sys try: client = MongoClient(host= ['localhost:27017'],",
"sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast",
"it first') sys.exit() result_dict = { \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\":",
"MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db = client.ast except: print('mongo isn\\'t currently",
"{ \"fors\": [], \"ifs\": [], \"lists\": [], \"listcomps\": [], \"dicts\": [], \"dictcomps\": [],",
"client.ast except: print('mongo isn\\'t currently running...please start it first') sys.exit() result_dict = {",
"<gh_stars>0 from pymongo import MongoClient import json import sys try: client = MongoClient(host=",
"except: print('mongo isn\\'t currently running...please start it first') sys.exit() result_dict = { \"fors\":",
"json import sys try: client = MongoClient(host= ['localhost:27017'], serverSelectionTimeoutMS = 2000) client.server_info() db",
"[], } def output_json(handle): results = handle.find( {}, {'_id': False } ).limit(25) for"
] |
[
"pack is passed successfully SUCCEEDED = 0 # pack is going to start",
"successfully SUCCEEDED = 0 # pack is going to start PREPARED = 1",
"= 2 # pack passing refused REFUSED = 3 # pack is destroyed",
"4 # unknown error with pack UNKNOWN = 9 # info-level INFO =",
"passing way ON_WAY = -1 # pack is passed successfully SUCCEEDED = 0",
"refused REFUSED = 3 # pack is destroyed DESTROYED = 4 # unknown",
"= 0 # pack is going to start PREPARED = 1 # pack",
"SUCCEEDED = 0 # pack is going to start PREPARED = 1 #",
"# pack is passed successfully SUCCEEDED = 0 # pack is going to",
"pack is on the passing way ON_WAY = -1 # pack is passed",
"# pack passing timeout TIMEOUT = 2 # pack passing refused REFUSED =",
"passed successfully SUCCEEDED = 0 # pack is going to start PREPARED =",
"<filename>SwitchTracer/cores/contrib/couriermiddlewares/status.py<gh_stars>0 # pack is on the passing way ON_WAY = -1 # pack",
"is going to start PREPARED = 1 # pack passing timeout TIMEOUT =",
"PREPARED = 1 # pack passing timeout TIMEOUT = 2 # pack passing",
"pack passing timeout TIMEOUT = 2 # pack passing refused REFUSED = 3",
"= 4 # unknown error with pack UNKNOWN = 9 # info-level INFO",
"# pack is destroyed DESTROYED = 4 # unknown error with pack UNKNOWN",
"start PREPARED = 1 # pack passing timeout TIMEOUT = 2 # pack",
"1 # pack passing timeout TIMEOUT = 2 # pack passing refused REFUSED",
"# pack passing refused REFUSED = 3 # pack is destroyed DESTROYED =",
"pack passing refused REFUSED = 3 # pack is destroyed DESTROYED = 4",
"pack is destroyed DESTROYED = 4 # unknown error with pack UNKNOWN =",
"= 3 # pack is destroyed DESTROYED = 4 # unknown error with",
"is passed successfully SUCCEEDED = 0 # pack is going to start PREPARED",
"# pack is on the passing way ON_WAY = -1 # pack is",
"way ON_WAY = -1 # pack is passed successfully SUCCEEDED = 0 #",
"ON_WAY = -1 # pack is passed successfully SUCCEEDED = 0 # pack",
"REFUSED = 3 # pack is destroyed DESTROYED = 4 # unknown error",
"is on the passing way ON_WAY = -1 # pack is passed successfully",
"# unknown error with pack UNKNOWN = 9 # info-level INFO = 100",
"passing timeout TIMEOUT = 2 # pack passing refused REFUSED = 3 #",
"destroyed DESTROYED = 4 # unknown error with pack UNKNOWN = 9 #",
"is destroyed DESTROYED = 4 # unknown error with pack UNKNOWN = 9",
"on the passing way ON_WAY = -1 # pack is passed successfully SUCCEEDED",
"DESTROYED = 4 # unknown error with pack UNKNOWN = 9 # info-level",
"passing refused REFUSED = 3 # pack is destroyed DESTROYED = 4 #",
"TIMEOUT = 2 # pack passing refused REFUSED = 3 # pack is",
"going to start PREPARED = 1 # pack passing timeout TIMEOUT = 2",
"timeout TIMEOUT = 2 # pack passing refused REFUSED = 3 # pack",
"-1 # pack is passed successfully SUCCEEDED = 0 # pack is going",
"the passing way ON_WAY = -1 # pack is passed successfully SUCCEEDED =",
"# pack is going to start PREPARED = 1 # pack passing timeout",
"3 # pack is destroyed DESTROYED = 4 # unknown error with pack",
"= 1 # pack passing timeout TIMEOUT = 2 # pack passing refused",
"0 # pack is going to start PREPARED = 1 # pack passing",
"to start PREPARED = 1 # pack passing timeout TIMEOUT = 2 #",
"2 # pack passing refused REFUSED = 3 # pack is destroyed DESTROYED",
"= -1 # pack is passed successfully SUCCEEDED = 0 # pack is",
"pack is going to start PREPARED = 1 # pack passing timeout TIMEOUT"
] |
[
"os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir,",
"open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with",
"tusaxml = input(\"Podaj ścieżkę do folderu z plikami xml: \") tusaoperaty = input(\"Podaj",
"os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy:",
"os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file),",
"file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with open(",
"4 pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml",
"dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if",
"in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1",
"input(\"Podaj ścieżkę do folderu z operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty):",
"bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as",
"dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for",
"bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do",
"subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs,",
"= subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in",
"for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with",
"z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami: \")",
") else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"),",
"if i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy:",
"os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write(",
"byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\")",
"bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir,",
"natsorted(stare_xml): if i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as",
"bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas",
"file) + \"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat,",
"os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file),",
"file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write(",
"brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu z plikami xml: \") tusaoperaty",
"print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się 4 pliki tekstowe: -",
"\") tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami: \") for subdir, dirs,",
"== os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir,",
"operat = subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file",
"= set() stare_xml = set() nowe_xml = set() count = 1 # aktualna",
"+ str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się 4 pliki",
"bibliotek import os import datetime import shutil from natsort import natsorted from natsort",
"file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat,",
"file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"),",
"os import datetime import shutil from natsort import natsorted from natsort import natsort_keygen",
"import natsort_keygen nkey = natsort_keygen() byly = set() stare_xml = set() nowe_xml =",
"os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy(",
"dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs, files",
"os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open(",
"do folderu z operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat",
"\"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml): if",
"+ \"\\n\") # czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec",
"as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file))",
"czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą",
"if os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as",
"file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files):",
"os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego",
"= datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość",
"pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml =",
"shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as",
"import bibliotek import os import datetime import shutil from natsort import natsorted from",
") as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml): if i",
"skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() /",
"open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i",
"+ \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir,",
"z operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir",
"else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\"",
"i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z",
") with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\")",
"datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się",
"file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy:",
"1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except:",
"dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir,",
"nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") #",
"with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for",
"byly = set() stare_xml = set() nowe_xml = set() count = 1 #",
"str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się 4 pliki tekstowe:",
"file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count +=",
"as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" )",
"if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat, file)): try:",
"+ \"\\n\") for i in natsorted(stare_xml): if i not in nowe_xml: with open(",
"- brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu z plikami xml: \")",
"\"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml,",
"folderu z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami:",
"<filename>move_xmls_p33.py<gh_stars>0 # -*- coding: utf-8 -*- # import bibliotek import os import datetime",
"udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml):",
"się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey)",
"\".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if not os.path.exists(os.path.join(operat, file)):",
"# -*- coding: utf-8 -*- # import bibliotek import os import datetime import",
"tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami: \") for subdir, dirs, _",
"-*- # import bibliotek import os import datetime import shutil from natsort import",
"i in natsorted(stare_xml): if i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\"",
"brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu z plikami xml:",
"file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir,",
"files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file)",
"_ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs, files in",
"subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")):",
"-*- coding: utf-8 -*- # import bibliotek import os import datetime import shutil",
"\"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"),",
"+ \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files",
"print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" + str(czaskoniec).split(\".\")[0]) input(\"Wciśnij ENTER aby wyjść...\")",
"stare_xml = set() nowe_xml = set() count = 1 # aktualna data i",
"if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with",
"i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i)",
"# aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA!",
"os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy:",
"in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not",
"aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W",
"do folderu z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu z",
"import shutil from natsort import natsorted from natsort import natsort_keygen nkey = natsort_keygen()",
"nowe_xml = set() count = 1 # aktualna data i godzina czasstart =",
"bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat)",
"count = 1 # aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" +",
"pojawić się 4 pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\"",
"trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania =",
"os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się",
"input(\"Podaj ścieżkę do folderu z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do",
"file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir,",
"file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat,",
"czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania",
"files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0]",
"as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu czaskoniec = datetime.datetime.now()",
"os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file)",
"os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat):",
"calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds()",
"- podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu",
"= 1 # aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0])",
"tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj",
"utf-8 -*- # import bibliotek import os import datetime import shutil from natsort",
"\"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się 4 pliki tekstowe: - bledy",
") as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu czaskoniec =",
"natsort_keygen nkey = natsort_keygen() byly = set() stare_xml = set() nowe_xml = set()",
"as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml): if i not",
"bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml): if i not in nowe_xml:",
"shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" )",
"print(count) count += 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat,",
"for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"):",
"\"\\n\") for i in natsorted(stare_xml): if i not in nowe_xml: with open( os.path.join(tusaxml,",
"natsort import natsorted from natsort import natsort_keygen nkey = natsort_keygen() byly = set()",
"not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) +",
"folderu z operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat =",
"file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs,",
"byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in",
"czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" %",
"= natsort_keygen() byly = set() stare_xml = set() nowe_xml = set() count =",
"xmlami mogą pojawić się 4 pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla",
"dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly:",
"\"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in",
") tusaxml = input(\"Podaj ścieżkę do folderu z plikami xml: \") tusaoperaty =",
"import natsorted from natsort import natsort_keygen nkey = natsort_keygen() byly = set() stare_xml",
"xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami: \") for subdir,",
"czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\"",
"plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu z operatami: \") for",
"shutil from natsort import natsorted from natsort import natsort_keygen nkey = natsort_keygen() byly",
"open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało",
"- brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu z plikami",
"natsort_keygen() byly = set() stare_xml = set() nowe_xml = set() count = 1",
"\"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), )",
"\"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\"",
"skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for",
"in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml,",
"file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", )",
"not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file)",
"- bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę",
"roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\")",
"natsort import natsort_keygen nkey = natsort_keygen() byly = set() stare_xml = set() nowe_xml",
"\"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file)",
"set() nowe_xml = set() count = 1 # aktualna data i godzina czasstart",
"bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy(",
"for i in natsorted(stare_xml): if i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"),",
"\"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml):",
"file) + \"\\n\") for i in natsorted(stare_xml): if i not in nowe_xml: with",
"się 4 pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" )",
"ścieżkę do folderu z operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey)",
"print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić się 4",
"nkey = natsort_keygen() byly = set() stare_xml = set() nowe_xml = set() count",
"with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas",
"if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if not",
"+= 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), )",
"natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"),",
"= roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" + str(czaskoniec).split(\".\")[0])",
") as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) else:",
"datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła",
"\"\\n\") # czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec -",
"- czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania)",
"= set() nowe_xml = set() count = 1 # aktualna data i godzina",
"60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" + str(czaskoniec).split(\".\")[0]) input(\"Wciśnij ENTER aby",
"bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in natsorted(stare_xml): if i not in",
"set() count = 1 # aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\"",
"os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey)",
"# czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart",
"= set() count = 1 # aktualna data i godzina czasstart = datetime.datetime.now()",
"in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] ==",
"mogą pojawić się 4 pliki tekstowe: - bledy - podmienione - brak_odpowiednika_dla_xmla -",
"with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie",
"os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) + \"\\n\") for i in",
"= czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\"",
"folderze z xmlami mogą pojawić się 4 pliki tekstowe: - bledy - podmienione",
"dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count)",
"import os import datetime import shutil from natsort import natsorted from natsort import",
"/ 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" + str(czaskoniec).split(\".\")[0]) input(\"Wciśnij ENTER",
"as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) else: try:",
"\") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for",
"= datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami mogą pojawić",
"+ \"\\tNie udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file),",
"\"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu czaskoniec",
"coding: utf-8 -*- # import bibliotek import os import datetime import shutil from",
"bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy:",
"stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if",
"not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with open(",
"from natsort import natsorted from natsort import natsort_keygen nkey = natsort_keygen() byly =",
"subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files):",
"in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\", ) as bledy: bledy.write(os.path.join(subdir, file) +",
"bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu czaskoniec = datetime.datetime.now() roznicaczas =",
"godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze z xmlami",
") byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file",
"\"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania calego skryptu",
"import datetime import shutil from natsort import natsorted from natsort import natsort_keygen nkey",
") as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\"",
"podmienione - brak_odpowiednika_dla_xmla - brak_nowego_xmla_dla_operatu\\n\\n\"\"\" ) tusaxml = input(\"Podaj ścieżkę do folderu z",
"operatami: \") for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat)",
"udało się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with",
"z xmlami mogą pojawić się 4 pliki tekstowe: - bledy - podmienione -",
"except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file) +",
"os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in",
"file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) +",
"for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.endswith((\".xml\",",
"1 # aktualna data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print(",
"data i godzina czasstart = datetime.datetime.now() print(\"~~~~~~START~~~~~~\\t\" + str(czasstart).split(\".\")[0]) print( \"\"\"\\n\\nUWAGA! W folderze",
") except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as bledy: bledy.write( os.path.join(subdir, file)",
"ścieżkę do folderu z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę do folderu",
"= input(\"Podaj ścieżkę do folderu z operatami: \") for subdir, dirs, _ in",
"nowe_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if",
"się skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open(",
"try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\"",
"in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\")",
"try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" )",
"W folderze z xmlami mogą pojawić się 4 pliki tekstowe: - bledy -",
"bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir, file)) nowe_xml.add(operat) for",
"# import bibliotek import os import datetime import shutil from natsort import natsorted",
"skopiować.\\n\" ) else: try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) with open( os.path.join(tusaxml,",
"subdir, dirs, files in os.walk(tusaxml): dirs.sort(key=nkey) for file in natsorted(files): if file.upper().endswith(\".XML\"): if",
"in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir, dirs, files in os.walk(tusaxml):",
"roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" + str(czaskoniec).split(\".\")[0]) input(\"Wciśnij",
"for file in natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count",
"os.path.join(subdir, file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml, \"bledy.txt\"), \"a\" ) as",
"os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file), ) except: with open( os.path.join(tusaxml,",
"natsorted from natsort import natsort_keygen nkey = natsort_keygen() byly = set() stare_xml =",
"czastrwania = roznicaczas.total_seconds() / 60 print(\"\\nCałość zajęła (minuty):\") print(\"%.2f\" % czastrwania) print(\"\\n~~~~~~KONIEC~~~~~~\\t\" +",
"for subdir, dirs, _ in os.walk(tusaoperaty): dirs.sort(key=nkey) operat = subdir stare_xml.add(operat) for subdir,",
"= input(\"Podaj ścieżkę do folderu z plikami xml: \") tusaoperaty = input(\"Podaj ścieżkę",
") as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" ) byly.add(os.path.join(subdir,",
"open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(i) + \"\\n\") # czas trwania",
"\"a\" ) as bledy: bledy.write( os.path.join(subdir, file) + \"\\tNie udało się skopiować.\\n\" )",
"set() stare_xml = set() nowe_xml = set() count = 1 # aktualna data",
"natsorted(files): if file.endswith((\".xml\", \".XML\")): if os.path.splitext(file)[0] == os.path.basename(operat): print(count) count += 1 if",
"in natsorted(stare_xml): if i not in nowe_xml: with open( os.path.join(tusaxml, \"brak_nowego_xmla_dla_operatu.txt\"), \"a\" )",
"datetime import shutil from natsort import natsorted from natsort import natsort_keygen nkey =",
"with open( os.path.join(tusaxml, \"podmienione.txt\"), \"a\" ) as bledy: bledy.write(os.path.join(operat, file) + \"\\n\") except:",
"if file.upper().endswith(\".XML\"): if os.path.join(subdir, file) not in byly: with open( os.path.join(tusaxml, \"brak_odpowiednika_dla_xmla.txt\"), \"a\",",
"czaskoniec = datetime.datetime.now() roznicaczas = czaskoniec - czasstart czastrwania = roznicaczas.total_seconds() / 60",
"count += 1 if not os.path.exists(os.path.join(operat, file)): try: shutil.copy( os.path.join(subdir, file), os.path.join(operat, file),",
"from natsort import natsort_keygen nkey = natsort_keygen() byly = set() stare_xml = set()"
] |
[
"0 RUNNING = 1 FAILED = 2 STOPPED = 3 PAUSED = 4",
"State(IntEnum): STARTING = 0 RUNNING = 1 FAILED = 2 STOPPED = 3",
"class State(IntEnum): STARTING = 0 RUNNING = 1 FAILED = 2 STOPPED =",
"IntEnum class State(IntEnum): STARTING = 0 RUNNING = 1 FAILED = 2 STOPPED",
"= 0 RUNNING = 1 FAILED = 2 STOPPED = 3 PAUSED =",
"from enum import IntEnum class State(IntEnum): STARTING = 0 RUNNING = 1 FAILED",
"STARTING = 0 RUNNING = 1 FAILED = 2 STOPPED = 3 PAUSED",
"import IntEnum class State(IntEnum): STARTING = 0 RUNNING = 1 FAILED = 2",
"enum import IntEnum class State(IntEnum): STARTING = 0 RUNNING = 1 FAILED ="
] |
[
"import path from .views import * app_name = 'users' urlpatterns = [ path('pagina-inicial',pagina_inicial_usuario,name='pagina-inicial-usuario')",
"from django.urls import path from .views import * app_name = 'users' urlpatterns =",
"django.urls import path from .views import * app_name = 'users' urlpatterns = [",
"path from .views import * app_name = 'users' urlpatterns = [ path('pagina-inicial',pagina_inicial_usuario,name='pagina-inicial-usuario') ]",
"<filename>users/urls.py<gh_stars>0 from django.urls import path from .views import * app_name = 'users' urlpatterns"
] |
[
"return (a == 10 or b == 10 or a + b ==",
"<reponame>arthxvr/coding--python def makes10(a, b): return (a == 10 or b == 10 or",
"b): return (a == 10 or b == 10 or a + b",
"makes10(a, b): return (a == 10 or b == 10 or a +",
"def makes10(a, b): return (a == 10 or b == 10 or a",
"(a == 10 or b == 10 or a + b == 10)"
] |
[
"0 else False return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh",
"# disable point lights self.scene.manual_exposure = 5.0 else: for i in range(self.lights): #",
"the location of the camera to fill the occ-matrix cell \"\"\" camera_mesh =",
"gripper sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise",
"torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back",
"1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt",
"each of the cameras. - Viewer mode: A full mesh is displayed at",
"disable point lights self.scene.manual_exposure = 5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction()",
"self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True",
"return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError def",
"transfer object state back into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2)",
"* len(objs) if scales is None else scales assert len(objs) == len(scales), \"provided",
"np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose)",
"= torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state",
"= np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle *",
"simulator; assumes that all other things have been taken care of. ''' if",
"360 for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet used!",
"else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh =",
"the camera position, camera-object position and the look-at parameter\"\"\" if objs is None:",
"obj in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene. Can be",
"self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates",
"def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj",
"update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera position, camera-object position and the",
"obj): \"\"\" Obtaining the bbox boundaries (pos + size for x,y,z) for a",
"cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions =",
"// 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel in",
"self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded = False",
"import random from typing import Tuple import numpy as np from copy import",
"''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError #",
"logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the appropriate",
"n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity",
"torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *=",
"obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel =",
"logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras =",
"np.pi / 180.) light_z = np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x,",
"the camera to fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode",
"RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader",
"Tuple import numpy as np from copy import deepcopy import torch import stillleben",
"cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera position, camera-object position",
"from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from",
"full mesh is displayed at the position and with the pose of the",
"self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone",
"Just calls the appropriate simulator; assumes that all other things have been taken",
"+= self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj): \"\"\"",
"(pos + size for x,y,z) for a given object\"\"\" obj_pose = obj.pose() offset_x,",
"= [(angle + default_ori_angle) % 360 for angle in cam_ori_angles] # TODO parameters",
"cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1)",
"False self.z_offset = 0. self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights ==",
"= np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] =",
"\"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can",
"the look-at parameter\"\"\" if objs is None: objs = [] scales = [1.0]",
"@property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self):",
"if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self):",
"obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0)",
"for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet used! for",
"6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel in zip(self.scene.objects,",
"overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just",
"\"\"\" Default setup_scene. Can be overriden from specific scenes \"\"\" _ = self.room_assembler.make_room()",
"if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state)",
"load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded:",
"def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes()",
"def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs = []",
"scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None):",
"A full mesh is displayed at the position and with the pose of",
"logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\")",
"nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action)",
"obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations = self.get_separations()",
"def is_there_collision(self): separations = self.get_separations() collision = True if np.sum(separations) < 0 else",
"= nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into the",
"for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"])",
"= False def setup_scene(self): \"\"\" Default setup_scene. Can be overriden from specific scenes",
"in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel)",
"# simulate timestep in nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state",
"back into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos,",
"yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist =",
"72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360 for angle in cam_ori_angles]",
"self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine",
"assert len(self.dynamic_objects) > 0, \"Objects must be added to dynamic_objects before computing collisions\"",
"loaded yet, load them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific",
"= cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1) other angles from a",
"add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj =",
"self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must be",
"from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\"",
"self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle *",
"deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name,",
"6) for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy,",
"self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0,",
"for defining scenarios \"\"\" config = dict() name = 'scenario' def __init__(self, cfg,",
"self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug",
"camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1",
"cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle)",
"import stillleben as sl import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from",
"raise NotImplementedError # TODO implement for gripper sim elif self.physics_engine == \"nimble\": if",
"setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap",
"\"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if",
"not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): '''",
"setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError",
"= torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0]",
"Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh,",
"deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1]",
"enabling physics simulation there. ''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\")",
"setup...\") if not self.meshes_loaded: self.load_meshes() # if objects have not been loaded yet,",
"= cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return",
"height) for a given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1] +",
"pose of the camera - Normal mode: A tiny-dummy obj is place on",
"obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] =",
"setup_camera_objs(self): \"\"\" Setting an object for each of the cameras. - Viewer mode:",
"= [torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates a",
"obj_vel.shape[0] // 6) for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose =",
"self.viewer_mode = cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader",
"= RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0.",
"import numpy as np from copy import deepcopy import torch import stillleben as",
"= dict() name = 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device =",
"360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi / 180.) *",
"-light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized =",
"camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist",
"+= self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the appropriate simulator; assumes that",
"= [], [] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel",
"cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera position,",
"object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset",
"all other things have been taken care of. ''' if self.physics_engine == \"physx\":",
"self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index)",
"= f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle,",
"elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle",
"displayed at the position and with the pose of the camera - Normal",
"np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle *",
"cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False,",
"obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj:",
"RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0. self.lights",
"in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose)",
"cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine",
"\"\"\" Obtaining the z_offset (z-pos + height) for a given object\"\"\" obj_pose =",
"raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if not",
"cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo",
"z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj):",
"scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj",
"= light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects",
"\"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self):",
"enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4)",
"180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return",
"def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self):",
"-> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity",
"mode: A full mesh is displayed at the position and with the pose",
"that all other things have been taken care of. ''' if self.physics_engine ==",
"timestep in nimblephysics. ''' # simulate timestep in nimble if action is None:",
"= pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity,",
"Creates a clone of the current stillleben scene for nimblephysics, enabling physics simulation",
"obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj,",
"self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False,",
"CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos =",
"cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def",
"is_there_collision(self): separations = self.get_separations() collision = True if np.sum(separations) < 0 else False",
"False def setup_scene(self): \"\"\" Default setup_scene. Can be overriden from specific scenes \"\"\"",
"self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def",
"degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1)",
"self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property",
"self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations",
"load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def",
"/ 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0,",
"= np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_y",
"def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if",
"self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self):",
"self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an object for each of the",
"in nimblephysics. ''' # simulate timestep in nimble if action is None: action",
"True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\"",
"= scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler =",
"the appropriate simulator; assumes that all other things have been taken care of.",
"an object z-position given a list of supporting objects\"\"\" if objs is None:",
"/ 180.) * np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle * np.pi",
"object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) /",
"obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset = torch.Tensor([-offset_x, -offset_y,",
"Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras",
"setup_nimble_(self): ''' Creates a clone of the current stillleben scene for nimblephysics, enabling",
"objs is None: objs = [] scales = [1.0] * len(objs) if scales",
"+= self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self,",
"if objects have not been loaded yet, load them self.setup_objects_() self.objects_loaded = True",
"reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded",
"given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1])",
"separations def is_there_collision(self): separations = self.get_separations() collision = True if np.sum(separations) < 0",
"obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def",
"setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self): '''",
"Can be overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self):",
"defining scenarios \"\"\" config = dict() name = 'scenario' def __init__(self, cfg, scene:",
"else False return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\")",
"done after everything else \"\"\" for obj in self.static_objects: obj.casts_shadows = False def",
"\"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def",
"angles that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] +",
"default ori. angle and (n_cameras-1) other angles from a linspace of angles that",
"be done after everything else \"\"\" for obj in self.static_objects: obj.casts_shadows = False",
"obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t",
"import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as",
"on the location of the camera to fill the occ-matrix cell \"\"\" camera_mesh",
"== \"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene()",
"light_x = np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.)",
"= ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False",
"camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True))",
"= [1.0] * len(objs) if scales is None else scales assert len(objs) ==",
"\"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs,",
"z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera",
"* np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle",
"is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index,",
"-1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix(",
"torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects) >",
"parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of the current stillleben scene",
"NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded:",
"random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions",
"pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi",
"360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360 for angle in",
"def sim_step_(self): ''' Just calls the appropriate simulator; assumes that all other things",
"return def finalize_scene(self): \"\"\" Scene setup stuff that has to be done after",
"''' Simulates a timestep in nimblephysics. ''' # simulate timestep in nimble if",
"adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can be overwritten by scenario-specific logic",
"self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return",
"torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure =",
"Obtaining the z_offset (z-pos + height) for a given object\"\"\" obj_pose = obj.pose()",
"self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt",
"5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle",
"of the current stillleben scene for nimblephysics, enabling physics simulation there. ''' print(\"initializing",
"angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX",
"the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id,",
"raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff",
"other angles from a linspace of angles that are 5 degrees apart default_ori_angle",
"\"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\"",
"e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an",
"return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos + size",
"camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1]",
"set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader)",
"lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None: self.scene.light_map",
"for obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1]",
"self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics. '''",
"yet, load them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific logic",
"dict() name = 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device",
"and the look-at parameter\"\"\" if objs is None: objs = [] scales =",
"scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene = scene if",
"import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import",
"else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle =",
"* camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self):",
"camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos + height) for a",
"obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel)",
"# e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting",
"cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose",
"from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import",
"default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles =",
"-1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating",
"+ torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure",
"setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera",
"vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)]",
"positions, velocities = [], [] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel,",
"= cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader =",
"self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True):",
"\"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera ->",
"= self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1) other",
"specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\"",
"4.0]) + torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized",
"180.) light_z = np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z])",
"physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of the current stillleben",
"obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t =",
"*= 0. # disable point lights self.scene.manual_exposure = 5.0 else: for i in",
"self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper sim elif self.physics_engine",
"= z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos +",
"torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i]",
"\"\"\" Updating the camera position, camera-object position and the look-at parameter\"\"\" if objs",
"\"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light =",
"is None: objs = [] scales = [1.0] * len(objs) if scales is",
"self.cameras_loaded = False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t",
"self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self):",
"camera, objs=None, scales=None): \"\"\" Updating the camera position, camera-object position and the look-at",
"linspace of angles that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles =",
"from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from",
"obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj)",
"logic, e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can be overwritten",
"self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False,",
"False return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_()",
"z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def",
"np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle *",
"camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\"",
"scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an object",
"class for defining scenarios \"\"\" import random from typing import Tuple import numpy",
"-1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj): \"\"\"",
"the pose of the camera - Normal mode: A tiny-dummy obj is place",
"numpy as np from copy import deepcopy import torch import stillleben as sl",
"cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\",",
"remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None):",
"finalize_scene(self): \"\"\" Scene setup stuff that has to be done after everything else",
"simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics. ''' # simulate timestep in",
"state back into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos =",
"pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions +",
"self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera,",
"self.cameras = [] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] #",
"/ torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects)",
"cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat =",
"False if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting()",
"stillleben scene for nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble scene from",
"if objs is None: objs = [] scales = [1.0] * len(objs) if",
"def simulate(self): ''' Can be overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt",
"nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader",
"cameras. - Viewer mode: A full mesh is displayed at the position and",
"is None else scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\"",
"def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise",
"for nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble scene from sl...\") #",
"simulation there. ''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world =",
"if np.sum(separations) < 0 else False return collision def load_meshes(self): \"\"\" \"\"\" if",
"= obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip",
"= self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2,",
"base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1) other angles from",
"(z-pos + height) for a given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2,",
"is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights",
"self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError",
"[(angle + default_ori_angle) % 360 for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max'",
"obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug)",
"obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel",
"object z-position given a list of supporting objects\"\"\" if objs is None: objs",
"= MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded",
"np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_y =",
"random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if",
"scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene)",
"if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only 1",
"calls the appropriate simulator; assumes that all other things have been taken care",
"% 360 for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet",
"= deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale",
"height adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can be overwritten by scenario-specific",
"camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos",
"separations = [obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def",
"ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of the current",
"Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\" config = dict() name =",
"be overriden from specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default",
"obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object,",
"for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs,",
"obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for",
"180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0,",
"apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles",
"cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name =",
"a clone of the current stillleben scene for nimblephysics, enabling physics simulation there.",
"print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions,",
"stuff that has to be done after everything else \"\"\" for obj in",
"decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff that has to",
"np from copy import deepcopy import torch import stillleben as sl import nimblephysics",
"collisions\" self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return",
"for obj in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene. Can",
"for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t",
"Obtaining the bbox boundaries (pos + size for x,y,z) for a given object\"\"\"",
"self.scene = scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler",
"from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import",
"been loaded yet, load them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\"",
"self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into the stillleben context obj_pos, obj_vel",
"False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self):",
"= False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t =",
"* np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle * np.pi / 180.)",
"setup...\") self.cameras = [] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"]",
"True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if",
"= [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle",
"the cameras. - Viewer mode: A full mesh is displayed at the position",
"= z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the",
"before computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects if hasattr(obj,",
"in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet used! for i, cam_ori_angle",
"collision = True if np.sum(separations) < 0 else False return collision def load_meshes(self):",
"NotImplementedError # TODO implement for gripper sim elif self.physics_engine == \"nimble\": if not",
"self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter:",
"= cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded =",
"\"\"\" import random from typing import Tuple import numpy as np from copy",
"torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3)",
"only 1 camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist",
"sl import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader",
"\"Objects must be added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation",
"5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1],",
"self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self):",
"np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi",
"True def simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics. ''' # simulate",
"look-at parameter\"\"\" if objs is None: objs = [] scales = [1.0] *",
"z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos + size for",
"simulate(self): ''' Can be overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_()",
"elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine",
"Scene setup stuff that has to be done after everything else \"\"\" for",
"CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1]",
"obj): \"\"\" Obtaining the z_offset (z-pos + height) for a given object\"\"\" obj_pose",
"self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs = [] cam_config = self.config[\"camera\"]",
"self.device = cfg.device self.viewer_mode = cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader",
"import object_info class Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\" config =",
"self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset =",
"sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants",
"if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects()",
"setup_scene. Can be overriden from specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self):",
"< 0 else False return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return",
"a linspace of angles that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles",
"self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights == 0 else None if",
"for gripper sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else:",
"into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0]",
"bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj)",
"/ 180.) * np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle * np.pi",
"import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class",
"dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects if",
"return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded",
"3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) #",
"camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2]",
"simulate timestep in nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state =",
"# if objects have not been loaded yet, load them self.setup_objects_() self.objects_loaded =",
"self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1) other angles",
"objects have not been loaded yet, load them self.setup_objects_() self.objects_loaded = True return",
"obj_pose = obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2",
"self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1]",
"self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure = 5.0",
"Abstract class for defining scenarios \"\"\" config = dict() name = 'scenario' def",
"self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def",
"print(\"camera setup...\") self.cameras = [] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat =",
"as CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class for defining",
"3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must be added to",
"= [obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self):",
"= cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine =",
"object state back into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos",
"= CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos",
"sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], []",
"clone of the current stillleben scene for nimblephysics, enabling physics simulation there. '''",
"appropriate simulator; assumes that all other things have been taken care of. '''",
"obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset =",
"lights self.scene.manual_exposure = 5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle =",
"= [] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick",
"import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as",
"utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity =",
"= vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX convention def",
"== \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for",
"sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes",
"there. ''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World()",
"# transfer object state back into the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(),",
"camera-object position and the look-at parameter\"\"\" if objs is None: objs = []",
"* np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle * np.pi / 180.)",
"self.meshes_loaded: self.load_meshes() # if objects have not been loaded yet, load them self.setup_objects_()",
"point lights self.scene.manual_exposure = 5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle",
"= torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3,",
"objs=None, scales=None): \"\"\" Updating an object z-position given a list of supporting objects\"\"\"",
"scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self,",
"self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else:",
"e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can be overwritten by",
"get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS",
"np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_z =",
"self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a",
"__init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene =",
"sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils",
"get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure = 5.0 else: for",
"to be done after everything else \"\"\" for obj in self.static_objects: obj.casts_shadows =",
"non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales):",
"if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations = self.get_separations() collision = True",
"- obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox",
"cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def",
"camera - Normal mode: A tiny-dummy obj is place on the location of",
"is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) #",
"obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy)",
"config = dict() name = 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device",
"len(objs) if scales is None else scales assert len(objs) == len(scales), \"provided non-matching",
"@property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self):",
"Normal mode: A tiny-dummy obj is place on the location of the camera",
"self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if objects have not",
"\"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None: self.scene.light_map =",
"Updating the camera position, camera-object position and the look-at parameter\"\"\" if objs is",
"= camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180),",
"camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh)",
"self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded",
"-1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi /",
"[obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations",
"setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None:",
"to fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ",
"return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos + height) for",
"self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates",
"= cfg.lightmap if self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras",
"scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose()",
"scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light",
"5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self):",
"in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat)",
"self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\"",
"\"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is",
"scenarios \"\"\" import random from typing import Tuple import numpy as np from",
"angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet used! for i,",
"boundaries (pos + size for x,y,z) for a given object\"\"\" obj_pose = obj.pose()",
"= cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False",
"np.sum(separations) < 0 else False return collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded:",
"ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity =",
"current stillleben scene for nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble scene",
"if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity))",
"in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3,",
"\"\"\" Abstract class for defining scenarios \"\"\" config = dict() name = 'scenario'",
"* np.pi / 180.) light_y = np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle",
"angles from a linspace of angles that are 5 degrees apart default_ori_angle =",
"cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in",
"for obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] =",
"random from typing import Tuple import numpy as np from copy import deepcopy",
"self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self):",
"supporting objects\"\"\" if objs is None: objs = [] scales = [1.0] *",
"= self.get_separations() collision = True if np.sum(separations) < 0 else False return collision",
"randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene = scene if randomize: utils.randomize()",
"nimblephysics. ''' # simulate timestep in nimble if action is None: action =",
"\"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj,",
"def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos + height) for a given",
"(n_cameras-1) other angles from a linspace of angles that are 5 degrees apart",
"new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into",
"typing import Tuple import numpy as np from copy import deepcopy import torch",
"* np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle",
"are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360,",
"None else scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose",
"parameter\"\"\" if objs is None: objs = [] scales = [1.0] * len(objs)",
"pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1]",
"the bbox boundaries (pos + size for x,y,z) for a given object\"\"\" obj_pose",
"light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. * light_color",
"\"\"\" Scene setup stuff that has to be done after everything else \"\"\"",
"static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos,",
"self.get_separations() collision = True if np.sum(separations) < 0 else False return collision def",
"Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object",
"return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if objects have not been",
"random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360 for angle",
"skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions",
"by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls",
"print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise",
"self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining",
"sim_step_(self): ''' Just calls the appropriate simulator; assumes that all other things have",
"self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap)",
"cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True)",
"4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] =",
"as sl import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import",
"pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return",
"added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj in",
"pick default ori. angle and (n_cameras-1) other angles from a linspace of angles",
"pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] =",
"= nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj in self.scene.objects: obj_info",
"obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True",
"yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.)",
"obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose)",
"\"\"\" if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if objects",
"return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine ==",
"np.pi / 180.) light_y = np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle *",
"bbox boundaries (pos + size for x,y,z) for a given object\"\"\" obj_pose =",
"def setup_camera_objs(self): \"\"\" Setting an object for each of the cameras. - Viewer",
"def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera position, camera-object position and",
"if self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras",
"i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat",
"\"\"\" Setting an object for each of the cameras. - Viewer mode: A",
"np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color =",
"supports only 1 camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo",
"camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose",
"else \"\"\" for obj in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default",
"= True def setup_camera_objs(self): \"\"\" Setting an object for each of the cameras.",
"be overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): '''",
"an object for each of the cameras. - Viewer mode: A full mesh",
"sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid",
"DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0. self.lights = cfg.lights self.lightmap",
"class Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\" config = dict() name",
"can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup",
"objs=None, scales=None): \"\"\" Updating the camera position, camera-object position and the look-at parameter\"\"\"",
"the stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] //",
"(obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the",
"3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity =",
"180.) * np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle * np.pi /",
"cfg.lightmap if self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras =",
"Simulates a timestep in nimblephysics. ''' # simulate timestep in nimble if action",
"= torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions",
"not self.meshes_loaded: self.load_meshes() # if objects have not been loaded yet, load them",
"is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod)",
"= [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat,",
"position and the look-at parameter\"\"\" if objs is None: objs = [] scales",
"= DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0. self.lights = cfg.lights",
"fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for",
"action=None): ''' Simulates a timestep in nimblephysics. ''' # simulate timestep in nimble",
"''' Just calls the appropriate simulator; assumes that all other things have been",
"self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height",
"of supporting objects\"\"\" if objs is None: objs = [] scales = [1.0]",
"CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class for defining scenarios",
"0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}'",
"# TODO implement for gripper sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded:",
"def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture()",
"def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff that has",
"overriden from specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup",
"''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt)",
"in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x",
"context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel",
"camera position, camera-object position and the look-at parameter\"\"\" if objs is None: objs",
"else scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" z_lookat =",
"offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset = torch.Tensor([-offset_x, -offset_y, offset_z])",
"self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded =",
"nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene,",
"self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self):",
"# utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for",
"= torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel):",
"obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj):",
"self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0. self.lights =",
"torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos,",
"flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod):",
"size for x,y,z) for a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z",
"cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not yet used! for i, cam_ori_angle in",
"= random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\"",
"self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt",
"list of supporting objects\"\"\" if objs is None: objs = [] scales =",
"print(f\"scenario '{self.name}' supports only 1 camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo",
"Setting an object for each of the cameras. - Viewer mode: A full",
"as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import",
"self.objects_loaded = False, False self.z_offset = 0. self.lights = cfg.lights self.lightmap = cfg.lightmap",
"def setup_scene(self): \"\"\" Default setup_scene. Can be overriden from specific scenes \"\"\" _",
"sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting",
"\"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras = []",
"= self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale",
"nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities",
"self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def",
"self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras()",
"[\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g.",
"of the camera to fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if",
"* scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None,",
"return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self,",
"f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle,",
"self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj in self.scene.objects:",
"= 0. self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights == 0 else",
"torch import stillleben as sl import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler",
"for obj in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations =",
"implement for gripper sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_()",
"all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects",
"obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back",
"obj is place on the location of the camera to fill the occ-matrix",
"= 3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must be added",
"Scenario-specific logic, e.g. height adjustment \"\"\" raise NotImplementedError def simulate(self): ''' Can be",
"self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the appropriate simulator; assumes that all",
"sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\" config",
"get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must be added to dynamic_objects before",
"stillleben as sl import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader",
"return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded:",
"self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the appropriate simulator; assumes",
"\"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if",
"\"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return",
"None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer",
"+ size for x,y,z) for a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y,",
"= cfg.device self.viewer_mode = cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader =",
"offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset = torch.Tensor([-offset_x, -offset_y, offset_z]) return offset",
"[\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist,",
"TODO implement for gripper sim elif self.physics_engine == \"nimble\": if not self.nimble_loaded: self.setup_nimble_()",
"/ 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g.",
"sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class for",
"def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None,",
"a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] +",
"cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment",
"z_offset (z-pos + height) for a given object\"\"\" obj_pose = obj.pose() z_offset =",
"k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360 for angle in cam_ori_angles] #",
"= obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset = torch.Tensor([-offset_x,",
"obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj",
"- Viewer mode: A full mesh is displayed at the position and with",
"self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_()",
"def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine == \"nimble\":",
"for a given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1]",
"have been taken care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine",
"obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene. Can be overriden from specific",
"* light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): #",
"= random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"]",
"object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states =",
"sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader",
"with the pose of the camera - Normal mode: A tiny-dummy obj is",
"obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX convention",
"cfg.device self.viewer_mode = cfg.viewer self.scene = scene if randomize: utils.randomize() self.mesh_loader = MeshLoader()",
"given a list of supporting objects\"\"\" if objs is None: objs = []",
"a list of supporting objects\"\"\" if objs is None: objs = [] scales",
"from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from",
"from specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting.",
"# pick default ori. angle and (n_cameras-1) other angles from a linspace of",
"def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat):",
"is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] +",
"\"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper",
"and with the pose of the camera - Normal mode: A tiny-dummy obj",
"mesh is displayed at the position and with the pose of the camera",
"2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6)",
"for defining scenarios \"\"\" import random from typing import Tuple import numpy as",
"if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific",
"def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return",
"= 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def",
"if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable",
"mode: A tiny-dummy obj is place on the location of the camera to",
"\"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj in",
"/ 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1])",
"MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap",
"self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos)",
"velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): '''",
"= camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] =",
"self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\" raise",
"True if np.sum(separations) < 0 else False return collision def load_meshes(self): \"\"\" \"\"\"",
"len(self.dynamic_objects) > 0, \"Objects must be added to dynamic_objects before computing collisions\" self.scene.check_collisions()",
"self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects",
":3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3])",
"len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose =",
"of the cameras. - Viewer mode: A full mesh is displayed at the",
"import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract class",
"for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info,",
"def setup_nimble_(self): ''' Creates a clone of the current stillleben scene for nimblephysics,",
"pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity",
"None else scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" z_lookat",
"+ default_ori_angle) % 360 for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are",
"# assert len(self.dynamic_objects) > 0, \"Objects must be added to dynamic_objects before computing",
"180.) light_y = np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi /",
"cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle +",
"import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import",
"in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose =",
"\"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper sim elif self.physics_engine == \"nimble\":",
"physics simulation there. ''' print(\"initializing nimble scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world",
"self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2,",
"cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs()",
"NotImplementedError def simulate(self): ''' Can be overwritten by scenario-specific logic ''' self.sim_t +=",
"light_z = np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i]",
"[1.0] * len(objs) if scales is None else scales assert len(objs) == len(scales),",
"position, camera-object position and the look-at parameter\"\"\" if objs is None: objs =",
"self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera -> ignoring n_cameras...\")",
"from a linspace of angles that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"]",
"ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi",
"\"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras):",
"self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement",
"action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object",
"cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt,",
"[torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates a timestep",
"''' # simulate timestep in nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs())",
"= cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera -> ignoring n_cameras...\") self.n_cameras",
"NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs =",
"= torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj,",
"object for each of the cameras. - Viewer mode: A full mesh is",
"z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) *",
"''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the appropriate simulator;",
"assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for",
"get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos + size for x,y,z) for",
"else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports",
"self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic",
"self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def",
"scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return",
"= utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity",
"cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position given a list of supporting",
"occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera",
"== len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj)",
"self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError",
"Can be overriden from specific scenes \"\"\" _ = self.room_assembler.make_room() def setup_lighting(self): \"\"\"",
"self.lightmap = cfg.lightmap if self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\", True):",
"light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0])",
"= np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.) light_z",
"2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos +",
"pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def",
"== 0 else None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario",
"return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat)",
"import Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import",
"setup_objects(self): \"\"\" \"\"\" if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() #",
"[] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj,",
"self.sim_step_() def sim_step_(self): ''' Just calls the appropriate simulator; assumes that all other",
"in self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations = self.get_separations() collision",
"obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel in zip(self.scene.objects, obj_pos,",
"dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError",
"self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded,",
"obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from",
"assumes that all other things have been taken care of. ''' if self.physics_engine",
"self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene. Can be overriden from",
"return separations def is_there_collision(self): separations = self.get_separations() collision = True if np.sum(separations) <",
"camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle *",
"from copy import deepcopy import torch import stillleben as sl import nimblephysics as",
"Abstract class for defining scenarios \"\"\" import random from typing import Tuple import",
"False, False if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene()",
"Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if self.lightmap is not",
"self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into the stillleben context",
"cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj)",
"self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh",
"import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import",
"vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3])",
"return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\" Updating the camera position, camera-object",
"z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos + height)",
"TODO parameters 'orientation_angle_min/max' are not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle",
") self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment \"\"\"",
"\"\"\" Updating an object z-position given a list of supporting objects\"\"\" if objs",
"self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] =",
"self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property",
"// 6) for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose()",
"sl_cutscenes.objects.object_loader import ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera",
"= utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi /",
"self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self,",
"import torch import stillleben as sl import nimblephysics as nimble from sl_cutscenes.room_models import",
"computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects if hasattr(obj, \"separation\")]",
"offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max offset = torch.Tensor([-offset_x, -offset_y, offset_z]) return",
"if scales is None else scales assert len(objs) == len(scales), \"provided non-matching scales",
"* np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color",
"after everything else \"\"\" for obj in self.static_objects: obj.casts_shadows = False def setup_scene(self):",
"scales=None): \"\"\" Updating the camera position, camera-object position and the look-at parameter\"\"\" if",
"= np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi /",
"= 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt =",
"assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose",
"self.nimble_world.setState(new_state) # transfer object state back into the stillleben context obj_pos, obj_vel =",
"care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise",
"sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static,",
"a timestep in nimblephysics. ''' # simulate timestep in nimble if action is",
"= cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded,",
"if not self.meshes_loaded: self.load_meshes() # if objects have not been loaded yet, load",
"**obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return",
"self.meshes_loaded, self.objects_loaded = False, False self.z_offset = 0. self.lights = cfg.lights self.lightmap =",
"_ = self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2,",
"# self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle",
"self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle",
"90) light_x = np.cos(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi /",
"obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\"",
"parameters 'orientation_angle_min/max' are not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle =",
"taken care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\":",
"cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug",
"= True def simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics. ''' #",
"\"\"\" Obtaining the bbox boundaries (pos + size for x,y,z) for a given",
"= torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) +",
"zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera def",
"sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class Scenario(object):",
"Viewer mode: A full mesh is displayed at the position and with the",
"to dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj in self.dynamic_objects",
"= 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects",
"[], [] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel =",
"self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self):",
"scale in zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose",
"for a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1]",
"= obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3]",
"= deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"]",
"have not been loaded yet, load them self.setup_objects_() self.objects_loaded = True return def",
"light_y = np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi / 180.)",
"[] scales = [1.0] * len(objs) if scales is None else scales assert",
"scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in",
"cam_ori_angles = [(angle + default_ori_angle) % 360 for angle in cam_ori_angles] # TODO",
"lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def",
"objs = [] scales = [1.0] * len(objs) if scales is None else",
"scales is None else scales assert len(objs) == len(scales), \"provided non-matching scales for",
"scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def sim_step_(self): ''' Just calls the",
"/ 180.) light_y = np.sin(ori_angle * np.pi / 180.) * np.cos(elev_angle * np.pi",
"cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist,",
"* scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the",
"* np.pi / 180.) light_z = np.sin(elev_angle * np.pi / 180.) light_direction =",
"+ height) for a given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1]",
"False, False, False if self.physics_engine == \"nimble\": self.nimble_loaded = False self.sim_t = 0",
"np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic,",
"'{self.name}' supports only 1 camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo =",
"= 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode =",
"vel.split([3, 3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX convention def add_object_to_scene(self,",
"-light_y, -light_z]) self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized",
"default_ori_angle) % 360 for angle in cam_ori_angles] # TODO parameters 'orientation_angle_min/max' are not",
"from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh",
"= True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_objects(self): \"\"\"",
"pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3,",
"a given object\"\"\" obj_pose = obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] -",
"Default setup_scene. Can be overriden from specific scenes \"\"\" _ = self.room_assembler.make_room() def",
"collision def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded =",
"= False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def",
"= cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales): z_pose +=",
"else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() #",
"be added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation for obj",
"scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1])",
"[0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360",
"name = 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode",
"''' Creates a clone of the current stillleben scene for nimblephysics, enabling physics",
"len(scales), \"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in",
"== \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper sim elif self.physics_engine ==",
"\"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\")",
"defining scenarios \"\"\" import random from typing import Tuple import numpy as np",
"light_color_normalized = 5. * light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0",
"camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2,",
"= camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle",
"been taken care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine ==",
"== len(scales), \"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale",
"= cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug =",
"roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height adjustment",
"stillleben context obj_pos, obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6)",
"as np from copy import deepcopy import torch import stillleben as sl import",
"cam_lookat = deepcopy(base_lookat) cam_name = f\"cam_{str(i).zfill(2)}\" cam_stereo_positions = [\"left\", \"right\"] if self.coplanar_stereo else",
"len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for",
"utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene)",
"copy import deepcopy import torch import stillleben as sl import nimblephysics as nimble",
"180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific logic, e.g. height",
"of angles that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0]",
"and (n_cameras-1) other angles from a linspace of angles that are 5 degrees",
"\"\"\" raise NotImplementedError def simulate(self): ''' Can be overwritten by scenario-specific logic '''",
"hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations = self.get_separations() collision = True if",
"None: objs = [] scales = [1.0] * len(objs) if scales is None",
"enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"], cam_config[\"distance_max\"]) cam_lookat = deepcopy(base_lookat) cam_name",
"import deepcopy import torch import stillleben as sl import nimblephysics as nimble from",
"np.cos(elev_angle * np.pi / 180.) light_y = np.sin(ori_angle * np.pi / 180.) *",
"place on the location of the camera to fill the occ-matrix cell \"\"\"",
"= utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded",
"{self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of the current stillleben scene for",
"tiny-dummy obj is place on the location of the camera to fill the",
"debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True def",
"setup_scene(self): \"\"\" Default setup_scene. Can be overriden from specific scenes \"\"\" _ =",
"def finalize_scene(self): \"\"\" Scene setup stuff that has to be done after everything",
"def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2]) if",
"0. # disable point lights self.scene.manual_exposure = 5.0 else: for i in range(self.lights):",
"np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x = np.cos(ori_angle * np.pi / 180.)",
":3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi",
"obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] =",
"True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera -> ignoring",
"0. self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights == 0 else None",
"DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera import sl_cutscenes.utils.utils as utils",
"self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if self.physics_engine",
"if self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs = [] cam_config =",
"position and with the pose of the camera - Normal mode: A tiny-dummy",
"get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset (z-pos + height) for a given object\"\"\"",
"\"right\"] if self.coplanar_stereo else [\"mono\"] self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions,",
"x,y,z) for a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3,",
"from typing import Tuple import numpy as np from copy import deepcopy import",
"elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper sim elif",
"timestep in nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world,",
"self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim()",
"= self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1]",
"self.z_offset = 0. self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights == 0",
"= object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos, vel = utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states",
"0.2, 0.2]) if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0.",
"light_color / torch.linalg.norm(light_color) self.scene.light_colors[i] = light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert",
"def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position given a list",
"nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader",
"used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist = random.uniform(cam_config[\"distance_min\"],",
"\"\"\" Abstract class for defining scenarios \"\"\" import random from typing import Tuple",
"def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene",
"objects\"\"\" if objs is None: objs = [] scales = [1.0] * len(objs)",
"\"\"\" for obj in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene.",
"= 5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360)",
"@property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self, pos,",
"= True if np.sum(separations) < 0 else False return collision def load_meshes(self): \"\"\"",
"nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into the stillleben",
"angle and (n_cameras-1) other angles from a linspace of angles that are 5",
"self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return",
"self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff that has to be",
"180.) * np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle * np.pi /",
"= light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. *",
"self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO implement for gripper sim",
"setup stuff that has to be done after everything else \"\"\" for obj",
"cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded, self.cameras_loaded = False, False, False if",
"positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None):",
"+ (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining",
"velocities = [], [] for obj in self.scene.objects: obj_info = object_info.get_object_by_class_id(obj.mesh.class_index) skel, pos,",
"obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries",
"for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh,",
"torch.eye(4) pose[:2, -1] = camera_pos[:2] pose[2, -1] = camera_pos[-1] + self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3]",
"that has to be done after everything else \"\"\" for obj in self.static_objects:",
"back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info,",
"self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff that has to be done",
"utils.sl_object_to_nimble(obj, obj_info, debug_mode=self.nimble_debug) self.nimble_world.addSkeleton(skel) positions.extend(pos) velocities.extend(vel) self.nimble_states = [torch.cat(positions + velocities)] self.nimble_loaded =",
"def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos + size for x,y,z)",
"\"separation\")] return separations def is_there_collision(self): separations = self.get_separations() collision = True if np.sum(separations)",
"torch.chunk(obj_vel, obj_vel.shape[0] // 6) for obj, pos, vel in zip(self.scene.objects, obj_pos, obj_vel): obj_pose",
"not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"]) cam_dist",
"True def setup_camera_objs(self): \"\"\" Setting an object for each of the cameras. -",
"are not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"], cam_config[\"elevation_angle_max\"])",
"None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure =",
"for x,y,z) for a given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z =",
"ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded = False, False self.z_offset",
"utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\" Abstract",
"def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return",
"+ random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) % 360 for",
"= self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx:",
"self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position",
"cfg.cam_dt self.physics_engine = cfg.physics_engine self.nimble_debug = cfg.nimble_debug self.reset_sim() return def reset_sim(self): self.meshes_loaded, self.objects_loaded,",
"the current stillleben scene for nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble",
"torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel, obj_vel.shape[0] //",
"= False, False self.z_offset = 0. self.lights = cfg.lights self.lightmap = cfg.lightmap if",
"cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def update_camera_height(self, camera, objs=None, scales=None): \"\"\"",
"+ velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates a timestep in",
"self.room_assembler.make_room() def setup_lighting(self): \"\"\" Default setup lighting. \"\"\" self.scene.ambient_light = torch.tensor([0.2, 0.2, 0.2])",
"separations = self.get_separations() collision = True if np.sum(separations) < 0 else False return",
"return print(\"camera setup...\") self.cameras = [] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat",
"class for defining scenarios \"\"\" config = dict() name = 'scenario' def __init__(self,",
"cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera -> ignoring n_cameras...\") self.n_cameras =",
"self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def",
"not been loaded yet, load them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self):",
"''' Can be overwritten by scenario-specific logic ''' self.sim_t += self.sim_dt self.sim_step_() def",
"in nimble if action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1],",
"obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] = obj_t obj.set_pose(obj_pose) angular_velocity, obj.linear_velocity = vel.split([3,",
"sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating",
"light_color_normalized self.scene.manual_exposure = 3.0 def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must",
"+ self.camera_objs[-1].mesh.bbox.min[-1] pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 *",
"def simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics. ''' # simulate timestep",
"bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object",
"len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj,",
"update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position given a list of",
"not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure",
"= torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. * light_color / torch.linalg.norm(light_color)",
"= True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise NotImplementedError def setup_cameras(self):",
"the position and with the pose of the camera - Normal mode: A",
"of the camera - Normal mode: A tiny-dummy obj is place on the",
"location of the camera to fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ",
"\"\"\" config = dict() name = 'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True):",
"[] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori. angle and",
"the z_offset (z-pos + height) for a given object\"\"\" obj_pose = obj.pose() z_offset",
"in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\" Default setup_scene. Can be overriden",
"cam_config[\"base_lookat\"] # pick default ori. angle and (n_cameras-1) other angles from a linspace",
"update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale in zip(objs, scales):",
"1 camera -> ignoring n_cameras...\") self.n_cameras = 1 self.coplanar_stereo = cfg.coplanar_stereo self.coplanar_stereo_dist =",
"0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property",
"obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh obj = self.object_loader.create_object(obj_info,",
"cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt = cfg.cam_dt",
"Updating an object z-position given a list of supporting objects\"\"\" if objs is",
"return self.object_loader.dynamic_objects def set_camera_look_at(self, pos, lookat): self.scene.set_camera_look_at(position=pos, look_at=lookat) def can_render(self): raise NotImplementedError def",
"for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat +=",
"scale camera.start_base_lookat[-1] = z_lookat return camera def get_obj_z_offset(self, obj): \"\"\" Obtaining the z_offset",
"things have been taken care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif",
"= cfg.lights self.lightmap = cfg.lightmap if self.lights == 0 else None if getattr(self,",
"obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat",
"= get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure = 5.0 else:",
"obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo,",
"import Tuple import numpy as np from copy import deepcopy import torch import",
"from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from sl_cutscenes.objects.object_loader import ObjectLoader from",
"for each of the cameras. - Viewer mode: A full mesh is displayed",
"else scales assert len(objs) == len(scales), \"provided non-matching scales for update_camera_height\" cur_obj_pose =",
"/ 180.) light_z = np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y,",
"self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def set_camera_look_at(self,",
"self.dynamic_objects if hasattr(obj, \"separation\")] return separations def is_there_collision(self): separations = self.get_separations() collision =",
"np.cos(elev_angle * np.pi / 180.) light_z = np.sin(elev_angle * np.pi / 180.) light_direction",
"load them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\"",
"object_info class Scenario(object): \"\"\" Abstract class for defining scenarios \"\"\" config = dict()",
"np.sin(elev_angle * np.pi / 180.) light_direction = torch.tensor([-light_x, -light_y, -light_z]) self.scene.light_directions[i] = light_direction",
"self.scene.light_directions[i] = light_direction light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5.",
"0.2]) if self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. #",
"them self.setup_objects_() self.objects_loaded = True return def setup_objects_(self): \"\"\" Scenario-specific logic \"\"\" raise",
"False, False self.z_offset = 0. self.lights = cfg.lights self.lightmap = cfg.lightmap if self.lights",
"is displayed at the position and with the pose of the camera -",
"raise NotImplementedError def simulate(self): ''' Can be overwritten by scenario-specific logic ''' self.sim_t",
"scene for nimblephysics, enabling physics simulation there. ''' print(\"initializing nimble scene from sl...\")",
"non-matching scales for update_camera_height\" cur_obj_pose = cur_obj.pose() z_pose = self.get_obj_z_offset(cur_obj) for obj, scale",
"the camera - Normal mode: A tiny-dummy obj is place on the location",
"self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position given",
"def load_meshes(self): \"\"\" \"\"\" if self.meshes_loaded: return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True",
"self.finalize_scene() @property def all_objects(self): return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def",
"i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90)",
"ObjectLoader from sl_cutscenes.objects.decorator_loader import DecoratorLoader from sl_cutscenes.lighting import get_lightmap from sl_cutscenes.camera import Camera",
"decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an object z-position given a",
"has to be done after everything else \"\"\" for obj in self.static_objects: obj.casts_shadows",
"0, \"Objects must be added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations =",
"cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded",
"scene from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities =",
"self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an object for each of",
"import nimblephysics as nimble from sl_cutscenes.room_models import RoomAssembler from sl_cutscenes.objects.mesh_loader import MeshLoader from",
"MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader = DecoratorLoader(scene=self.scene) self.meshes_loaded, self.objects_loaded =",
"scales = [1.0] * len(objs) if scales is None else scales assert len(objs)",
"pose[:3, :3] = utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle *",
"self.cameras.append(Camera(cam_name, self.cam_dt, cam_elev_angle, cam_ori_angle, cam_dist, cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific",
"angular_velocity.flip(0) # flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static:",
"getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only 1 camera",
"self.lightmap is not None: self.scene.light_map = get_lightmap(self.lightmap) self.scene.light_directions *= 0. # disable point",
"adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an object for each",
"= [] scales = [1.0] * len(objs) if scales is None else scales",
"everything else \"\"\" for obj in self.static_objects: obj.casts_shadows = False def setup_scene(self): \"\"\"",
"None if getattr(self, \"allow_multiple_cameras\", True): self.n_cameras = cfg.cameras else: print(f\"scenario '{self.name}' supports only",
"> 0, \"Objects must be added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations",
"= obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset def get_obj_offset(self,",
"[] self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default",
"cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene = scene",
"action is None: action = torch.zeros(self.nimble_world.getNumDofs()) new_state = nimble.timestep(self.nimble_world, self.nimble_states[-1], action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state)",
"self.camera_objs = [] cam_config = self.config[\"camera\"] base_lookat = cam_config[\"base_lookat\"] # pick default ori.",
"return print(\"mesh setup...\") self.load_meshes_() self.meshes_loaded = True def load_meshes_(self): \"\"\" Scenario-specific logic \"\"\"",
"z-position given a list of supporting objects\"\"\" if objs is None: objs =",
"def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene",
"ori. angle and (n_cameras-1) other angles from a linspace of angles that are",
"* np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180), roll=torch.tensor(0.) )",
"obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3,",
"A tiny-dummy obj is place on the location of the camera to fill",
"sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer self.scene = scene if randomize:",
"NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\" Scene setup stuff that",
"3]) obj.angular_velocity = angular_velocity.flip(0) # flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh:",
"print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if objects have not been loaded",
"raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of the",
"# flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool,",
"= angular_velocity.flip(0) # flip back from ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh],",
"cfg.lights self.lightmap = cfg.lightmap if self.lights == 0 else None if getattr(self, \"allow_multiple_cameras\",",
"**obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self, obj: sl.Object, decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx)",
"decrement_ins_idx: bool=True): self.scene.remove_object(obj) self.object_loader.remove_object(obj.instance_index, decrement_ins_idx=decrement_ins_idx) def update_object_height(self, cur_obj, objs=None, scales=None): \"\"\" Updating an",
"# TODO parameters 'orientation_angle_min/max' are not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles):",
"Camera import sl_cutscenes.utils.utils as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info",
"obj_vel = torch.chunk(new_state.clone(), 2) obj_pos = torch.chunk(obj_pos, obj_pos.shape[0] // 6) obj_vel = torch.chunk(obj_vel,",
"light_color = torch.tensor([4.0, 4.0, 4.0]) + torch.rand(3) light_color_normalized = 5. * light_color /",
"if self.objects_loaded: return print(\"object setup...\") if not self.meshes_loaded: self.load_meshes() # if objects have",
"cam_lookat, self.coplanar_stereo_dist, cam_stereo_positions, self.cam_movement_complexity)) self.setup_cameras_() # e.g. scenario-specific height adjustment self.setup_camera_objs() self.cameras_loaded =",
"must be added to dynamic_objects before computing collisions\" self.scene.check_collisions() separations = [obj.separation for",
"scenarios \"\"\" config = dict() name = 'scenario' def __init__(self, cfg, scene: sl.Scene,",
"given object\"\"\" obj_pose = obj.pose() offset_x, offset_y, offset_z = obj_pose[:3, -1] + obj.mesh.bbox.max",
"= cfg.coplanar_stereo self.coplanar_stereo_dist = cfg.coplanar_stereo_dist self.cam_movement_complexity = cfg.cam_movement_complexity self.sim_dt = cfg.sim_dt self.cam_dt =",
"scales=None): \"\"\" Updating an object z-position given a list of supporting objects\"\"\" if",
"from sl...\") # utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [],",
"for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30,",
"= cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle",
"= obj_info_mesh obj = self.object_loader.create_object(obj_info, obj_mesh, is_static, **obj_mod) self.scene.add_object(obj) return obj def remove_obj_from_scene(self,",
"in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) * scale camera.start_base_lookat[-1] = z_lookat return camera",
"scales for update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat",
"self.load_meshes() # if objects have not been loaded yet, load them self.setup_objects_() self.objects_loaded",
"utils.get_rot_matrix( yaw=torch.tensor(camera.ori_angle * np.pi / 180), pitch=torch.tensor(-1 * camera.elev_angle * np.pi / 180),",
"convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh = obj_info_mesh",
"'orientation_angle_min/max' are not yet used! for i, cam_ori_angle in enumerate(cam_ori_angles): cam_elev_angle = random.uniform(cam_config[\"elevation_angle_min\"],",
"zip(self.scene.objects, obj_pos, obj_vel): obj_pose = obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3]",
"self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos() camera_info_mesh = self.mesh_loader.get_meshes()[-1] self.camera_objs.append(self.add_object_to_scene(camera_info_mesh, is_static=True)) pose = torch.eye(4) pose[:2,",
"/ 2 return z_offset def get_obj_offset(self, obj): \"\"\" Obtaining the bbox boundaries (pos",
"z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return cur_obj def",
"self.scene.light_directions *= 0. # disable point lights self.scene.manual_exposure = 5.0 else: for i",
"if randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader",
"utils.dump_sl_scene_to_urdf(self.scene, \"scene.urdf\") self.nimble_world = nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj",
"= [0] + random.sample(np.linspace(0, 360, 72+1).tolist()[1:-1], k=self.n_cameras-1) cam_ori_angles = [(angle + default_ori_angle) %",
"raise NotImplementedError def setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs",
"at the position and with the pose of the camera - Normal mode:",
"nimble.simulation.World() self.nimble_world.setTimeStep(self.sim_dt) positions, velocities = [], [] for obj in self.scene.objects: obj_info =",
"range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0, 360) elev_angle = np.random.uniform(30, 90) light_x =",
"setup_cameras(self): if self.cameras_loaded: return print(\"camera setup...\") self.cameras = [] self.camera_objs = [] cam_config",
"height adjustment self.setup_camera_objs() self.cameras_loaded = True def setup_camera_objs(self): \"\"\" Setting an object for",
"camera to fill the occ-matrix cell \"\"\" camera_mesh = CONSTANTS.CAMERA_OBJ if self.viewer_mode else",
"\"nimble\": self.nimble_loaded = False self.sim_t = 0 self.setup_scene() self.setup_lighting() self.setup_objects() self.setup_cameras() self.decorate_scene() self.finalize_scene()",
"* np.pi / 180), roll=torch.tensor(0.) ) self.camera_objs[-1].set_pose(pose) self.scene.add_object(self.camera_objs[-1]) return def setup_cameras_(self): \"\"\" Scenario-specific",
"that are 5 degrees apart default_ori_angle = cam_config[\"orientation_angle_default\"] cam_ori_angles = [0] + random.sample(np.linspace(0,",
"as utils import sl_cutscenes.constants as CONSTANTS from sl_cutscenes import object_info class Scenario(object): \"\"\"",
"obj.pose() obj_rpy, obj_t = pos.split([3, 3]) obj_pose[:3, :3] = utils.get_mat_from_rpy(obj_rpy) obj_pose[:3, 3] =",
"ZYX convention def add_object_to_scene(self, obj_info_mesh: Tuple[object_info.ObjectInfo, sl.Mesh], is_static: bool, **obj_mod): obj_info, obj_mesh =",
"z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj) *",
"of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError",
"deepcopy import torch import stillleben as sl import nimblephysics as nimble from sl_cutscenes.room_models",
"look_at=lookat) def can_render(self): raise NotImplementedError def decorate_scene(self): self.room_assembler.add_wall_furniture() self.decorator_loader.decorate_scene(object_loader=self.object_loader) return def finalize_scene(self): \"\"\"",
"if self.viewer_mode else CONSTANTS.DUMMY_CAMERA_OBJ for camera_id, camera in enumerate(self.cameras): self.mesh_loader.load_meshes(camera_mesh) camera_pos = camera.get_pos()",
"else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\") def setup_nimble_(self): ''' Creates a clone of",
"velocities)] self.nimble_loaded = True def simulate_nimble_(self, action=None): ''' Simulates a timestep in nimblephysics.",
"action) self.nimble_states.append(new_state) self.nimble_world.setState(new_state) # transfer object state back into the stillleben context obj_pos,",
"zip(objs, scales): z_pose += self.get_obj_z_offset(obj) * scale cur_obj_pose[2, -1] = z_pose cur_obj.set_pose(cur_obj_pose) return",
"else: print(f\"scenario '{self.name}' supports only 1 camera -> ignoring n_cameras...\") self.n_cameras = 1",
"randomize: utils.randomize() self.mesh_loader = MeshLoader() self.object_loader = ObjectLoader(scenario_reset=True) self.room_assembler = RoomAssembler(scene=self.scene) self.decorator_loader =",
"'scenario' def __init__(self, cfg, scene: sl.Scene, randomize=True): self.device = cfg.device self.viewer_mode = cfg.viewer",
"return self.object_loader.all_objects @property def static_objects(self): return self.object_loader.static_objects @property def dynamic_objects(self): return self.object_loader.dynamic_objects def",
"self.scene.manual_exposure = 5.0 else: for i in range(self.lights): # self.scene.choose_random_light_direction() ori_angle = np.random.uniform(0,",
"is place on the location of the camera to fill the occ-matrix cell",
"= obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return",
"if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt) elif self.physics_engine == \"physx_manipulation_sim\": raise NotImplementedError # TODO",
"- Normal mode: A tiny-dummy obj is place on the location of the",
"obj.pose() z_offset = obj_pose[2, -1] + (obj.mesh.bbox.max[-1] - obj.mesh.bbox.min[-1]) / 2 return z_offset",
"other things have been taken care of. ''' if self.physics_engine == \"physx\": self.scene.simulate(self.sim_dt)",
"update_camera_height\" z_lookat = deepcopy(camera.start_base_lookat[-1]) for obj, scale in zip(objs, scales): z_lookat += self.get_obj_z_offset(obj)",
"== \"nimble\": if not self.nimble_loaded: self.setup_nimble_() self.simulate_nimble_() else: raise ValueError(f\"invalid physics_engine parameter: {self.physics_engine}\")",
"def get_separations(self): # assert len(self.dynamic_objects) > 0, \"Objects must be added to dynamic_objects"
] |
[
"extend to easily test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\"",
"-*- # Copyright (c) 2014, <NAME> # # Released under the MIT license",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR",
"to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"deal in # the Software without restriction, including without limitation the rights to",
"granted, free of charge, to any person obtaining a copy of # this",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION",
"time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end = time.time() print(end - start) \"\"\"",
"MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"to deal in # the Software without restriction, including without limitation the rights",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"restriction, including without limitation the rights to use, # copy, modify, merge, publish,",
"distribute, sublicense, and/or sell copies of the # Software, and to permit persons",
"application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code",
"easily test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine =",
"2014, <NAME> # # Released under the MIT license # # Permission is",
"= sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None)",
"publish, distribute, sublicense, and/or sell copies of the # Software, and to permit",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION #",
"documentation files (the \"Software\"), to deal in # the Software without restriction, including",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"do so, # subject to the following conditions: # # The above copyright",
"def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"as users import sqlalchemy as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class",
"def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\",",
"included in all # copies or substantial portions of the Software. # #",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from",
"conditions: # # The above copyright notice and this permission notice shall be",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the # Software, and",
"self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def",
"# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the #",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"= \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\"))",
"DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import unittest import",
"app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"]",
"# Copyright (c) 2014, <NAME> # # Released under the MIT license #",
"obtaining a copy of # this software and associated documentation files (the \"Software\"),",
"of charge, to any person obtaining a copy of # this software and",
"the Software without restriction, including without limitation the rights to use, # copy,",
"test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\",",
"class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id",
"app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_",
"UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id =",
"OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER",
"without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense,",
"to the following conditions: # # The above copyright notice and this permission",
"app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE",
"# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"asgard.application as application import asgard.users as users import sqlalchemy as sa app =",
"DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code using the database.\"\"\" def setUp(self):",
"class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code using the database.\"\"\" def",
"license # # Permission is hereby granted, free of charge, to any person",
"tune the turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start",
"\"\"\"Class to extend to easily test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"]",
"from __future__ import unicode_literals, print_function, absolute_import import unittest import asgard.application as application import",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals, print_function,",
"[\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"# Released under the MIT license # # Permission is hereby granted, free",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"the turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start =",
"all # copies or substantial portions of the Software. # # THE SOFTWARE",
"sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to",
"WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF",
"copies of the # Software, and to permit persons to whom the Software",
"app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id =",
"pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_)",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\")",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE",
"self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None)",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals,",
"app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just used",
"# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"to any person obtaining a copy of # this software and associated documentation",
"[\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ =",
"WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"including without limitation the rights to use, # copy, modify, merge, publish, distribute,",
"permission notice shall be included in all # copies or substantial portions of",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"the MIT license # # Permission is hereby granted, free of charge, to",
"AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"\"\"\" # not run consistently, just used to tune the turns for pbkdf2",
"notice and this permission notice shall be included in all # copies or",
"under the MIT license # # Permission is hereby granted, free of charge,",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT,",
"sublicense, and/or sell copies of the # Software, and to permit persons to",
"turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time()",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A",
"ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE",
"app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily",
"sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose()",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR",
"= \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction()",
"OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine =",
"the following conditions: # # The above copyright notice and this permission notice",
"and associated documentation files (the \"Software\"), to deal in # the Software without",
"and to permit persons to whom the Software is furnished to do so,",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id,",
"Copyright (c) 2014, <NAME> # # Released under the MIT license # #",
"\"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self):",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH",
"\"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\",",
"run consistently, just used to tune the turns for pbkdf2 def test_time(self): hash_",
"app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None,",
"self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\"))",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"to permit persons to whom the Software is furnished to do so, #",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT",
"app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"]",
"to extend to easily test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] =",
"Software without restriction, including without limitation the rights to use, # copy, modify,",
"def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"]",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR #",
"test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\"))",
"software and associated documentation files (the \"Software\"), to deal in # the Software",
"test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\")",
"consistently, just used to tune the turns for pbkdf2 def test_time(self): hash_ =",
"\"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\"))",
"code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine",
"\"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\"))",
"def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end",
"= app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"copy of # this software and associated documentation files (the \"Software\"), to deal",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\")",
"= app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end = time.time() print(end",
"SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not",
"and/or sell copies of the # Software, and to permit persons to whom",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE",
"\"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id",
"import unittest import asgard.application as application import asgard.users as users import sqlalchemy as",
"in all # copies or substantial portions of the Software. # # THE",
"app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"the Software is furnished to do so, # subject to the following conditions:",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\"))",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE",
"a copy of # this software and associated documentation files (the \"Software\"), to",
"sell copies of the # Software, and to permit persons to whom the",
"Released under the MIT license # # Permission is hereby granted, free of",
"as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend",
"in # the Software without restriction, including without limitation the rights to use,",
"-*- coding: utf-8 -*- # Copyright (c) 2014, <NAME> # # Released under",
"= app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code using the",
"merge, publish, distribute, sublicense, and/or sell copies of the # Software, and to",
"\"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"use, # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"= app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None,",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the # Software,",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"]",
"is furnished to do so, # subject to the following conditions: # #",
"IN THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import unittest import asgard.application",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"__future__ import unicode_literals, print_function, absolute_import import unittest import asgard.application as application import asgard.users",
"app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\"))",
"app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\")",
"and this permission notice shall be included in all # copies or substantial",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN #",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE",
"associated documentation files (the \"Software\"), to deal in # the Software without restriction,",
"app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run",
"None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self):",
"the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:')",
"print_function, absolute_import import unittest import asgard.application as application import asgard.users as users import",
"hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end = time.time()",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"utf-8 -*- # Copyright (c) 2014, <NAME> # # Released under the MIT",
"limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN",
"# subject to the following conditions: # # The above copyright notice and",
"for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\",",
"= app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\"))",
"LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND",
"app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end = time.time() print(end -",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just used to tune",
"OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import",
"\"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] =",
"app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\")",
"<gh_stars>0 # -*- coding: utf-8 -*- # Copyright (c) 2014, <NAME> # #",
"None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\",",
"persons to whom the Software is furnished to do so, # subject to",
"\"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id,",
"\"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"# Software, and to permit persons to whom the Software is furnished to",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT",
"\"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\"",
"DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR",
"# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"notice shall be included in all # copies or substantial portions of the",
"import sqlalchemy as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class",
"any person obtaining a copy of # this software and associated documentation files",
"of the # Software, and to permit persons to whom the Software is",
"app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\"))",
"shall be included in all # copies or substantial portions of the Software.",
"files (the \"Software\"), to deal in # the Software without restriction, including without",
"# this software and associated documentation files (the \"Software\"), to deal in #",
"The above copyright notice and this permission notice shall be included in all",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\"",
"\"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def",
"app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine",
"import asgard.users as users import sqlalchemy as sa app = application.Asgard(__name__) app_users =",
"(c) 2014, <NAME> # # Released under the MIT license # # Permission",
"setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\"))",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS",
"app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None,",
"<NAME> # # Released under the MIT license # # Permission is hereby",
"id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def",
"# not run consistently, just used to tune the turns for pbkdf2 def",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import",
"= application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test",
"using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine =",
"import unicode_literals, print_function, absolute_import import unittest import asgard.application as application import asgard.users as",
"charge, to any person obtaining a copy of # this software and associated",
"THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import unittest import asgard.application as",
"# # The above copyright notice and this permission notice shall be included",
"\"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\"))",
"to tune the turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time",
"# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ =",
"\"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just",
"self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end = time.time() print(end - start)",
"app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_unicode(self):",
"= self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\"))",
"\"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\")",
"just used to tune the turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\")",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"to do so, # subject to the following conditions: # # The above",
"to whom the Software is furnished to do so, # subject to the",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"\"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just used to",
"be included in all # copies or substantial portions of the Software. #",
"unicode_literals, print_function, absolute_import import unittest import asgard.application as application import asgard.users as users",
"\"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just used to tune the",
"\"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_",
"USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import",
"furnished to do so, # subject to the following conditions: # # The",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"the # Software, and to permit persons to whom the Software is furnished",
"= \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] =",
"self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently, just used to tune the turns",
"\"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\"))",
"unittest import asgard.application as application import asgard.users as users import sqlalchemy as sa",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"\"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\",",
"permit persons to whom the Software is furnished to do so, # subject",
"whom the Software is furnished to do so, # subject to the following",
"\"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__()",
"test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\"))",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import time start = time.time() app_users.UsersManager.i._check_password(\"test\", hash_) end =",
"free of charge, to any person obtaining a copy of # this software",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR",
"of # this software and associated documentation files (the \"Software\"), to deal in",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"\"abcéèçÔx\")) \"\"\" # not run consistently, just used to tune the turns for",
"\"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\"",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"None, None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"hereby granted, free of charge, to any person obtaining a copy of #",
"self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def",
"= app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans = app.transaction() self.trans.__enter__() def tearDown(self):",
"so, # subject to the following conditions: # # The above copyright notice",
"# The above copyright notice and this permission notice shall be included in",
"IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"above copyright notice and this permission notice shall be included in all #",
"application import asgard.users as users import sqlalchemy as sa app = application.Asgard(__name__) app_users",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\"))",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"self.trans = app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine",
"not run consistently, just used to tune the turns for pbkdf2 def test_time(self):",
"hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id,",
"# -*- coding: utf-8 -*- # Copyright (c) 2014, <NAME> # # Released",
"used to tune the turns for pbkdf2 def test_time(self): hash_ = app_users.UsersManager.i._encode_password(\"<PASSWORD>\") import",
"app.transaction() self.trans.__enter__() def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None,",
"app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\",",
"without restriction, including without limitation the rights to use, # copy, modify, merge,",
"sqlalchemy as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"person obtaining a copy of # this software and associated documentation files (the",
"this permission notice shall be included in all # copies or substantial portions",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS #",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE",
"app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code using the database.\"\"\"",
"\"Software\"), to deal in # the Software without restriction, including without limitation the",
"# copies or substantial portions of the Software. # # THE SOFTWARE IS",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"coding: utf-8 -*- # Copyright (c) 2014, <NAME> # # Released under the",
"import asgard.application as application import asgard.users as users import sqlalchemy as sa app",
"test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine",
"(the \"Software\"), to deal in # the Software without restriction, including without limitation",
"asgard.users as users import sqlalchemy as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin)",
"= \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" # not run consistently,",
"following conditions: # # The above copyright notice and this permission notice shall",
"this software and associated documentation files (the \"Software\"), to deal in # the",
"app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__() self.trans =",
"MIT license # # Permission is hereby granted, free of charge, to any",
"NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"as application import asgard.users as users import sqlalchemy as sa app = application.Asgard(__name__)",
"OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self): app_users.config[\"preferred_encryption\"]",
"= app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id, \"xyz\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) def test_bcrypt_compatibility(self):",
"is hereby granted, free of charge, to any person obtaining a copy of",
"def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\"",
"database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine)",
"self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self): id = app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) app_users.UsersManager.i.set_password(id,",
"# # Released under the MIT license # # Permission is hereby granted,",
"def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] = \"bcrypt\" app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) \"\"\" #",
"= app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"bcrypt\")) app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\")",
"\"xyz\")) app_users.UsersManager.i.set_password(id, \"abc\") hash_ = app_users.UsersManager.i.read_by_id(id, [\"password_hash\"])[\"password_hash\"] self.assertTrue(hash_.startswith(\"werkzeug\")) self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def",
"SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import unittest import asgard.application as application",
"copyright notice and this permission notice shall be included in all # copies",
"users import sqlalchemy as sa app = application.Asgard(__name__) app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase):",
"Software is furnished to do so, # subject to the following conditions: #",
"app_users = app.register_plugin(users.UsersPlugin) class DbTest(unittest.TestCase): \"\"\"Class to extend to easily test code using",
"absolute_import import unittest import asgard.application as application import asgard.users as users import sqlalchemy",
"Software, and to permit persons to whom the Software is furnished to do",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"None) class UsersTest(DbTest): def test_base(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abc\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abc\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"xyz\")) def test_change_password(self):",
"the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell",
"def tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class",
"tearDown(self): self.trans.__exit__(None, None, None) app.engine.dispose() app.engine = self.tmp_engine app.__exit__(None, None, None) class UsersTest(DbTest):",
"IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"OTHER DEALINGS IN THE SOFTWARE. from __future__ import unicode_literals, print_function, absolute_import import unittest",
"# the Software without restriction, including without limitation the rights to use, #",
"\"xyz\")) def test_unicode(self): app_users.UsersManager.i.create_user(\"<EMAIL>\", \"abcéèçÔ\") self.assertTrue(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔ\")) self.assertFalse(app_users.UsersManager.i.test_user(\"<EMAIL>\", \"abcéèçÔx\")) def test_unicode_bcrypt(self): app_users.config[\"preferred_encryption\"] =",
"to easily test code using the database.\"\"\" def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine",
"OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR",
"subject to the following conditions: # # The above copyright notice and this",
"def setUp(self): app_users.config[\"preferred_encryption\"] = \"werkzeug\" self.tmp_engine = app.engine app.engine = sa.create_engine('sqlite:///:memory:') app.metadata.create_all(app.engine) app.__enter__()"
] |
[
"place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process)",
"= SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides byte",
"import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context",
"message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit",
"process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process) context.addEmit(emit) context.execute()",
"edna.process import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context",
"edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main():",
"EmptyStringSerializer() # twitter already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"),",
"encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess()",
"emit_serializer = EmptyStringSerializer() # twitter already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer,",
"from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def",
"tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\"))",
"bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"),",
"= EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides byte encoded message ingest",
"from edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer",
"edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer",
"twitter already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"),",
"user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest)",
"KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context =",
"= TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer,",
"TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"),",
"BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process) context.addEmit(emit) context.execute() if __name__==\"__main__\":",
"# twitter already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"),",
"import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer()",
"SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides byte encoded",
"SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() #",
"already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\"))",
"import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer =",
"import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import",
"from edna.ingest.streaming import TwitterStreamingIngest from edna.process import BaseProcess from edna.emit import KafkaEmit from",
"EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer()",
"EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides byte encoded message ingest =",
"edna.ingest.streaming import TwitterStreamingIngest from edna.process import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer",
"edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer =",
"= BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process) context.addEmit(emit) context.execute() if",
"provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process",
"TwitterStreamingIngest from edna.process import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer",
"ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit =",
"def main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter",
"main(): context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already",
"= EmptyStringSerializer() # twitter already provides byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"),",
"from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext def main(): context = SimpleStreamingContext()",
"media_fields=context.getVariable(\"media_fields\")) process = BaseProcess() emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process) context.addEmit(emit)",
"ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides byte encoded message",
"from edna.process import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from",
"context = SimpleStreamingContext() ingest_serializer = EmptyStringSerializer() emit_serializer = EmptyStringSerializer() # twitter already provides",
"BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import EmptyStringSerializer from edna.core.execution.context import SimpleStreamingContext",
"emit = KafkaEmit(serializer=emit_serializer, kafka_topic=context.getVariable(\"kafka_topic\"), bootstrap_server=context.getVariable(\"bootstrap_server\"), bootstrap_port=context.getVariable(\"bootstrap_port\")) context.addIngest(ingest) context.addProcess(process) context.addEmit(emit) context.execute() if __name__==\"__main__\": main()",
"byte encoded message ingest = TwitterStreamingIngest(serializer=ingest_serializer, bearer_token=context.getVariable(\"bearer_token\"), tweet_fields=context.getVariable(\"tweet_fields\"), user_fields=context.getVariable(\"user_fields\"), place_fields=context.getVariable(\"place_fields\"), media_fields=context.getVariable(\"media_fields\")) process =",
"import TwitterStreamingIngest from edna.process import BaseProcess from edna.emit import KafkaEmit from edna.serializers.EmptySerializer import"
] |
[] |
[
"pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION,",
"names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1, 2, 3], index_col=0, dtype=str, )",
"-> pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL,",
"pd from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL =",
"pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'],",
"f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return",
"version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df() ->",
"'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature",
"index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df(",
"coding: utf-8 -*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd from ..path_utils import",
"index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature family",
"return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str,",
"def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION,",
"miRBase.\"\"\" import pandas as pd from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION",
"'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df(",
"dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX,",
"2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return",
"dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() ->",
"pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'],",
"ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, )",
"names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return",
") def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\" return",
"to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, )",
"= 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL =",
"ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz'",
"'22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz'",
"PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA",
"get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[",
"= f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX,",
"ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get",
") def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL,",
"def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION,",
"return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame:",
"-> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key',",
"PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1, 2, 3],",
"miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ],",
"-*- coding: utf-8 -*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd from ..path_utils",
"= f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df()",
"return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1,",
"version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\"",
"mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id',",
"PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame:",
"PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature",
"miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2],",
"= f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\"",
"PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df()",
"\"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0,",
"'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get",
"<filename>src/pyobo/sources/mirbase_constants.py # -*- coding: utf-8 -*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd",
"'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz'",
"ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1, 2,",
"'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature",
"premature miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'],",
"\"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous',",
"\"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0,",
"names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame:",
"PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE",
"PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def",
"pandas as pd from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION = '22.1'",
"f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() ->",
"miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str,",
"1, 2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\"",
"def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION,",
"..path_utils import ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL",
"dtype=str, ) def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX,",
"f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature",
"import ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL =",
"version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() ->",
"get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key',",
"from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz'",
"version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1, 2, 3], index_col=0, dtype=str,",
"2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature",
"as pd from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL",
"usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame: \"\"\"Get mature miRNA",
"dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0,",
"f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz'",
"-> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id',",
"for miRBase.\"\"\" import pandas as pd from ..path_utils import ensure_df PREFIX = 'mirbase'",
"premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def",
"def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\" return ensure_df(",
"PREFIX = 'mirbase' VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL",
"premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1,",
"import pandas as pd from ..path_utils import ensure_df PREFIX = 'mirbase' VERSION =",
"pd.DataFrame: \"\"\"Get mature miRNA dataframe.\"\"\" return ensure_df( PREFIX, MATURE_URL, version=VERSION, names=[ 'mature_key', 'name',",
"= f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE =",
"1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to",
"family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2],",
"premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1,",
"PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def",
"dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\"",
"= '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL =",
"return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str,",
"'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get",
"ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, )",
"VERSION = '22.1' PREFAM_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_prefam.txt.gz' PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL",
"PREMATURE_TO_PREFAMILY_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_2_prefam.txt.gz' PREMATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def",
"names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_mature_df() -> pd.DataFrame:",
"PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df(",
") def get_premature_df() -> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL,",
"# -*- coding: utf-8 -*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd from",
"\"\"\"Constants for miRBase.\"\"\" import pandas as pd from ..path_utils import ensure_df PREFIX =",
"get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key',",
"MATURE_URL, version=VERSION, names=[ 'mature_key', 'name', 'previous', 'mirbase.mature_id', ], usecols=[0, 1, 2, 3], index_col=0,",
"f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL,",
"= f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna.txt.gz' MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get",
"\"\"\"Get premature miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key',",
"MATURE_URL = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_mature.txt.gz' PREMATURE_TO_MATURE = f'ftp://mirbase.org/pub/mirbase/{VERSION}/database_files/mirna_pre_mature.txt.gz' def get_premature_family_df() -> pd.DataFrame: \"\"\"Get premature family",
"dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id', 'mirna_name'], usecols=[0, 1, 2], index_col=0,",
"-*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd from ..path_utils import ensure_df PREFIX",
"get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA to premature family dataframe.\"\"\" return ensure_df( PREFIX,",
"utf-8 -*- \"\"\"Constants for miRBase.\"\"\" import pandas as pd from ..path_utils import ensure_df",
"-> pd.DataFrame: \"\"\"Get premature miRNA dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_URL, version=VERSION, names=['premature_key', 'mirbase_id',",
"PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df()",
"family dataframe.\"\"\" return ensure_df( PREFIX, PREMATURE_TO_PREFAMILY_URL, version=VERSION, names=['premature_key', 'prefamily_key'], dtype=str, ) def get_premature_df()",
"dataframe.\"\"\" return ensure_df( PREFIX, PREFAM_URL, version=VERSION, names=['prefamily_key', 'family_id', 'family_name'], usecols=[0, 1, 2], index_col=0,",
"usecols=[0, 1, 2], index_col=0, dtype=str, ) def get_premature_to_prefamily_df() -> pd.DataFrame: \"\"\"Get premature miRNA"
] |
[
"')).strip().lower()[0] while cont not in 'sn': cont = str(input('Quer continuar a resistar [S/N]?",
"print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while",
"idade >= 18: maior += 1 if sexo == 'm': macho += 1",
"== 'm': macho += 1 if sexo == 'f' and idade < 20:",
"18: maior += 1 if sexo == 'm': macho += 1 if sexo",
"str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer",
"o seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior += 1 if",
"sexo == 'f' and idade < 20: menor += 1 while sexo not",
"resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn': cont = str(input('Quer continuar a",
"= 0 while True: idade = int(input('Qual a sua idade? ')) sexo =",
"+= 1 if sexo == 'f' and idade < 20: menor += 1",
"anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres com menos de 20",
"resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break print('=' * 50) print(f'Foram resistadas",
"1 if sexo == 'm': macho += 1 if sexo == 'f' and",
"str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn': cont =",
"')).strip().lower()[0] if cont == 'n': break print('=' * 50) print(f'Foram resistadas {maior} pessoas",
"if idade >= 18: maior += 1 if sexo == 'm': macho +=",
"sua idade? ')) sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade",
"'mf': sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m')",
"menor += 1 while sexo not in 'mf': sexo = str(input('Qual o seu",
"[M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]?",
"'sn': cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont == 'n':",
"== 'n': break print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores de 18",
"break print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram",
"continuar a resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break print('=' * 50)",
"'m': macho += 1 if sexo == 'f' and idade < 20: menor",
"20: menor += 1 while sexo not in 'mf': sexo = str(input('Qual o",
"resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas",
"{maior} pessoas maiores de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor}",
"idade? ')) sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade >=",
"True: idade = int(input('Qual a sua idade? ')) sexo = str(input('Qual o seu",
"0 while True: idade = int(input('Qual a sua idade? ')) sexo = str(input('Qual",
"= int(input('Qual a sua idade? ')) sexo = str(input('Qual o seu sexo [M/F]?",
"if sexo == 'f' and idade < 20: menor += 1 while sexo",
"cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn':",
"= str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn': cont",
"menor = 0 while True: idade = int(input('Qual a sua idade? ')) sexo",
"print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram resistados",
"+= 1 while sexo not in 'mf': sexo = str(input('Qual o seu sexo",
"cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break",
"'' maior = macho = menor = 0 while True: idade = int(input('Qual",
"[M/F]? ')).strip().lower()[0] if idade >= 18: maior += 1 if sexo == 'm':",
"')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0]",
"sexo == 'm': macho += 1 if sexo == 'f' and idade <",
"= macho = menor = 0 while True: idade = int(input('Qual a sua",
"seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar a",
"maiores de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres com",
"a sua idade? ')) sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if",
"idade = int(input('Qual a sua idade? ')) sexo = str(input('Qual o seu sexo",
">= 18: maior += 1 if sexo == 'm': macho += 1 if",
"+= 1 if sexo == 'm': macho += 1 if sexo == 'f'",
"not in 'mf': sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido",
"50) print(f'Foram resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram resistados {macho} homens.')",
"sexo = '' maior = macho = menor = 0 while True: idade",
"seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior += 1 if sexo",
"= str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont =",
"idade < 20: menor += 1 while sexo not in 'mf': sexo =",
"= menor = 0 while True: idade = int(input('Qual a sua idade? '))",
"< 20: menor += 1 while sexo not in 'mf': sexo = str(input('Qual",
"int(input('Qual a sua idade? ')) sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0]",
"continuar a resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn': cont = str(input('Quer",
"not in 'sn': cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont",
"[S/N]? ')).strip().lower()[0] while cont not in 'sn': cont = str(input('Quer continuar a resistar",
"a resistar [S/N]? ')).strip().lower()[0] while cont not in 'sn': cont = str(input('Quer continuar",
"sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar a resistar",
"if cont == 'n': break print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores",
"cont == 'n': break print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores de",
"pessoas maiores de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres",
"maior = macho = menor = 0 while True: idade = int(input('Qual a",
"maior += 1 if sexo == 'm': macho += 1 if sexo ==",
"while cont not in 'sn': cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0]",
"a resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break print('=' * 50) print(f'Foram",
"')).strip().lower()[0] if idade >= 18: maior += 1 if sexo == 'm': macho",
"sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont not in",
"1 if sexo == 'f' and idade < 20: menor += 1 while",
"'f' and idade < 20: menor += 1 while sexo not in 'mf':",
"print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres com menos de 20 anos.')",
"inserido com sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont",
"sexo not in 'mf': sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto",
"print(f'Foram resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram",
"if sexo == 'm': macho += 1 if sexo == 'f' and idade",
"in 'mf': sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com",
"sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont",
"de 18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres com menos",
"str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior += 1",
"= str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break print('='",
"* 50) print(f'Foram resistadas {maior} pessoas maiores de 18 anos.') print(f'Foram resistados {macho}",
"and idade < 20: menor += 1 while sexo not in 'mf': sexo",
"= str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior +=",
"')) sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18:",
"str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont == 'n': break print('=' *",
"macho = menor = 0 while True: idade = int(input('Qual a sua idade?",
"1 while sexo not in 'mf': sexo = str(input('Qual o seu sexo [M/F]?",
"sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior",
"while sexo not in 'mf': sexo = str(input('Qual o seu sexo [M/F]? ')).strip().lower()[0]",
"in 'sn': cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if cont ==",
"= '' maior = macho = menor = 0 while True: idade =",
"macho += 1 if sexo == 'f' and idade < 20: menor +=",
"cont not in 'sn': cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] if",
"'n': break print('=' * 50) print(f'Foram resistadas {maior} pessoas maiores de 18 anos.')",
"18 anos.') print(f'Foram resistados {macho} homens.') print(f'Foram resistadas {menor} mulheres com menos de",
"sexo [M/F]? ')).strip().lower()[0] if idade >= 18: maior += 1 if sexo ==",
"[S/N]? ')).strip().lower()[0] if cont == 'n': break print('=' * 50) print(f'Foram resistadas {maior}",
"o seu sexo [M/F]? ')).strip().lower()[0] print('\\033[31mResisto inserido com sucesso!\\033[m') cont = str(input('Quer continuar",
"== 'f' and idade < 20: menor += 1 while sexo not in",
"com sucesso!\\033[m') cont = str(input('Quer continuar a resistar [S/N]? ')).strip().lower()[0] while cont not",
"while True: idade = int(input('Qual a sua idade? ')) sexo = str(input('Qual o"
] |
[
"= int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을",
"stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일",
"c_list = [file for file in file_list if file.endswith(\".c\")] # java_list = [file",
"Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice == 4:",
"subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as ex: branch = str(\"error\") msg",
"choice = int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif",
"분을 n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) #",
"걸 백그라운드에서 실행 except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex)",
"= int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일 생성 시간) % 60n을",
"New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create time backup mode\") print(\"5.",
"file_list if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True)",
"i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as ex:",
"가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정",
"elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file",
": \")) num = int(input('Enter the minutes you want to set up :",
"auto commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh',",
"time import os # auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh',",
"GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼",
"# java_list = [file for file in file_list if file.endswith(\".java\")] for i in",
"'./userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh'])",
"Time backup mode\") print(\"4. Create time backup mode\") print(\"5. Error Backup mode\") print(\"6.",
"해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break",
"createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime)",
"as dt import subprocess import time import os # auto commit 실행 def",
"subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif",
"stop_time_timestamp # (현재 시간 - 파일 생성 시간) % 60n을 통해서 나머지 계산",
"Create time backup mode\") print(\"5. Error Backup mode\") print(\"6. Git add file\") print(\"7.",
"= (stop - start(filename)) % (60 * n) return time_remainder # 나머지가 0이",
"'./setting.sh']) filename = str(input(\"Enter your file name : \")) num = int(input('Enter the",
"0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가",
"= [file for file in file_list if file.endswith(\".java\")] for i in range(len(py_list)): try:",
"print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create time backup",
"중'을 출력 print(remainder(filename, start, stop, n)) # 나머지 출력 if remainder(filename, start, stop,",
"[file for file in file_list if file.endswith(\".py\")] # c_list = [file for file",
"[file for file in file_list if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python',",
"파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성",
"float형 숫자로 바꾼 후, float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp",
"# auto commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename])",
"Git add file\") print(\"7. Git push to branch\") print(\"8. Exit\") choice = int(input(\">>",
"GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex: #",
"name : \")) num = int(input('Enter the minutes you want to set up",
"if os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) #",
"# 출력 형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형",
"n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일",
"세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성",
"if file.endswith(\".py\")] # c_list = [file for file in file_list if file.endswith(\".c\")] #",
"'시도 중'을 출력 print(remainder(filename, start, stop, n)) # 나머지 출력 if remainder(filename, start,",
"branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice ==",
"'./TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2.",
"'./autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \"))",
"'./autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3:",
"print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create time backup mode\")",
"def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를",
"int(input('Enter the minutes you want to set up : ')) # GUI에서 사용자가",
"time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice",
"java_list = [file for file in file_list if file.endswith(\".java\")] for i in range(len(py_list)):",
"subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() #",
"\")) num = int(input('Enter the minutes you want to set up : '))",
"'./killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name : \")) num =",
"elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file",
"set up : ')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True:",
"while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\")",
"'./TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을",
"# auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh'])",
"threading import datetime as dt import subprocess import time import os # auto",
"Exception as ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh'])",
"#break elif choice == 5: path = \"./code/\" file_list = os.listdir(path) py_list =",
"= str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh'])",
"ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을 출력",
"GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh'])",
"실행 except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if :",
"stop(), n) # 파일 생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행",
"'./continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to",
"= \"./code/\" file_list = os.listdir(path) py_list = [file for file in file_list if",
"int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로",
"print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num):",
"file name : ')) # GUI에서 사용자가 특정 파일 선택했다고 가정 n =",
"n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def",
"push?(branch_name) \")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh',",
"중\") # 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n)) #",
"elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg",
"commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다",
"subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where",
"n) == 0: # auto commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음",
"= [file for file in file_list if file.endswith(\".c\")] # java_list = [file for",
"0: # auto commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh',",
"import schedule import threading import datetime as dt import subprocess import time import",
"해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice == 5: path = \"./code/\" file_list",
"up : ')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True: try:",
"= createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로",
"# 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\")",
"현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def stop(): stop_time",
"subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name : ')) #",
"commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit)",
"실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit",
"commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice",
"subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else: print(\"Wrong Input! Please input",
"schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime =",
"print(\"5. Error Backup mode\") print(\"6. Git add file\") print(\"7. Git push to branch\")",
"= str(input('Enter your file name : ')) # GUI에서 사용자가 특정 파일 선택했다고",
"분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼",
"try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을 기준으로 n분마다 auto",
"minutes you want to set up : ')) # GUI에서 사용자가 분을 세팅했다고",
"subprocess import time import os # auto commit 실행 def auto_commit(): print(\"auto commit을",
"choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4.",
"timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def stop(): stop_time =",
"= int(input('Enter the minutes you want to set up : ')) # GUI에서",
"\")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash',",
"나머지 출력 if remainder(filename, start, stop, n) == 0: # auto commit 실행",
"'./autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else: print(\"Wrong Input! Please input again\")",
"(현재 시간 - 파일 생성 시간) % 60n을 통해서 나머지 계산 def remainder(filename,",
"== 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write",
"start, stop, n): time_remainder = (stop - start(filename)) % (60 * n) return",
"stop, n) == 0: # auto commit 실행 - subprocess에서 에러가 계속 나서",
"branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else:",
"name : ')) # GUI에서 사용자가 특정 파일 선택했다고 가정 n = int(input('Enter",
"n) return time_remainder # 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop,",
"time_remainder # 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도",
"print(\"3. Time backup mode\") print(\"4. Create time backup mode\") print(\"5. Error Backup mode\")",
"# (현재 시간 - 파일 생성 시간) % 60n을 통해서 나머지 계산 def",
"start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해",
"가정 n = int(input('Enter the minutes you want to set up : '))",
"if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except",
"되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가 실행될",
"바꾼 후, float형을 int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp())",
"int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일 생성 시간) % 60n을 통해서",
"start, stop, n) == 0: # auto commit 실행 - subprocess에서 에러가 계속",
"file in file_list if file.endswith(\".c\")] # java_list = [file for file in file_list",
"변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재",
"py_list[0]], universal_newlines=True) except Exception as ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh',",
"start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def",
"함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n)) # 나머지 출력",
"'./killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name : ')) # GUI에서",
"출력 if remainder(filename, start, stop, n) == 0: # auto commit 실행 -",
"= str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6:",
"Backup mode\") print(\"6. Git add file\") print(\"7. Git push to branch\") print(\"8. Exit\")",
"mode\") print(\"6. Git add file\") print(\"7. Git push to branch\") print(\"8. Exit\") choice",
"return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환",
"for file in file_list if file.endswith(\".c\")] # java_list = [file for file in",
"branch = str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh',",
"n)) # 나머지 출력 if remainder(filename, start, stop, n) == 0: # auto",
"path = \"./code/\" file_list = os.listdir(path) py_list = [file for file in file_list",
"filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch =",
": ')) # GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception",
"= dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를",
"datetime as dt import subprocess import time import os # auto commit 실행",
"\")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8:",
"you want to set up : ')) # GUI에서 사용자가 분을 n으로 세팅했다고",
"\"./code/\" file_list = os.listdir(path) py_list = [file for file in file_list if file.endswith(\".py\")]",
"\")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh'])",
"'./addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice != 8: print(\"Menu\")",
"Error Backup mode\") print(\"6. Git add file\") print(\"7. Git push to branch\") print(\"8.",
"in file_list if file.endswith(\".c\")] # java_list = [file for file in file_list if",
"int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp #",
"branch\") print(\"8. Exit\") choice = int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh'])",
"n): print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop,",
"출력 print(remainder(filename, start, stop, n)) # 나머지 출력 if remainder(filename, start, stop, n)",
"n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception as ex: # GUI에서 체크버튼",
"remainder(filename, start, stop, n) == 0: # auto commit 실행 - subprocess에서 에러가",
"str(input('Enter your file name : ')) # GUI에서 사용자가 특정 파일 선택했다고 가정",
"try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as ex: branch = str(\"error\")",
"사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서",
"% (60 * n) return time_remainder # 나머지가 0이 되면 autocommit 실행 def",
"def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을",
"n) # 파일 생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except",
"숫자로 바꾼 후, float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp =",
"in file_list if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]],",
"# GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh',",
"== 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh',",
"# GUI에서 사용자가 특정 파일 선택했다고 가정 n = int(input('Enter the minutes you",
"elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash',",
"'./continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename =",
"Exit\") choice = int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh'])",
"# 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create time",
"schedule import threading import datetime as dt import subprocess import time import os",
"stop, n): print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start,",
"add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7:",
"num = int(input('Enter the minutes you want to set up : ')) #",
"출력 형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로",
"in file_list if file.endswith(\".py\")] # c_list = [file for file in file_list if",
"이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now()",
"= os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의",
"file in file_list if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path +",
"as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash',",
"start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형",
"subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to",
"'./autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your",
"시간 - 파일 생성 시간) % 60n을 통해서 나머지 계산 def remainder(filename, start,",
"if file.endswith(\".c\")] # java_list = [file for file in file_list if file.endswith(\".java\")] for",
"filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice != 8: print(\"Menu\") print(\"1.",
"path + py_list[0]], universal_newlines=True) except Exception as ex: branch = str(\"error\") msg =",
"to set up : ')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정 while",
"n = int(input('Enter the minutes you want to set up : ')) #",
"def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간",
"= str(input(\"Enter your file name : \")) num = int(input('Enter the minutes you",
"push to branch\") print(\"8. Exit\") choice = int(input(\">> \")) if choice == 1:",
"set up : ')) # GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num)",
"= int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice",
"Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서",
"filename = str(input('Enter your file name : ')) # GUI에서 사용자가 특정 파일",
"== 0: # auto commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh',",
"True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을 기준으로 n분마다",
"# GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정",
"start, stop, n)) # 나머지 출력 if remainder(filename, start, stop, n) == 0:",
"create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return",
"해제2\") #break elif choice == 5: path = \"./code/\" file_list = os.listdir(path) py_list",
"choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh',",
"def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성 ymd_ctime =",
"subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name : \")) num = int(input('Enter",
"시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception as ex: #",
"file\") print(\"7. Git push to branch\") print(\"8. Exit\") choice = int(input(\">> \")) if",
"2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh'])",
"file_list if file.endswith(\".c\")] # java_list = [file for file in file_list if file.endswith(\".java\")]",
"mode\") print(\"4. Create time backup mode\") print(\"5. Error Backup mode\") print(\"6. Git add",
"= os.listdir(path) py_list = [file for file in file_list if file.endswith(\".py\")] # c_list",
"float형 숫자로 바꾼 후, float형을 int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp",
"[file for file in file_list if file.endswith(\".c\")] # java_list = [file for file",
"생성 시간) % 60n을 통해서 나머지 계산 def remainder(filename, start, stop, n): time_remainder",
"생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception as ex:",
"# c_list = [file for file in file_list if file.endswith(\".c\")] # java_list =",
"print(remainder(filename, start, stop, n)) # 나머지 출력 if remainder(filename, start, stop, n) ==",
"'./killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit message: \"))",
"8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create time",
"start, stop(), n) # 파일 생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서",
"\")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2:",
"import subprocess import time import os # auto commit 실행 def auto_commit(): print(\"auto",
"choice == 5: path = \"./code/\" file_list = os.listdir(path) py_list = [file for",
"Git push to branch\") print(\"8. Exit\") choice = int(input(\">> \")) if choice ==",
"파일 생성 시간) % 60n을 통해서 나머지 계산 def remainder(filename, start, stop, n):",
"file.endswith(\".py\")] # c_list = [file for file in file_list if file.endswith(\".c\")] # java_list",
"subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name : \")) num",
"createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼",
"your file name : \")) num = int(input('Enter the minutes you want to",
"return stop_time_timestamp # (현재 시간 - 파일 생성 시간) % 60n을 통해서 나머지",
"float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp",
"파일 선택했다고 가정 n = int(input('Enter the minutes you want to set up",
"file in file_list if file.endswith(\".py\")] # c_list = [file for file in file_list",
": # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice == 5:",
"3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name : \"))",
"if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh',",
"try: print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex)",
"os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로",
"시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while",
"minutes you want to set up : ')) # GUI에서 사용자가 분을 n으로",
"import os # auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh'])",
"file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice",
"if remainder(filename, start, stop, n) == 0: # auto commit 실행 - subprocess에서",
"subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else: print(\"Wrong Input!",
"timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def start(filename): start_time =",
"str(input(\"Enter your file name : \")) num = int(input('Enter the minutes you want",
"os.listdir(path) py_list = [file for file in file_list if file.endswith(\".py\")] # c_list =",
"* n) return time_remainder # 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start,",
"to branch\") print(\"8. Exit\") choice = int(input(\">> \")) if choice == 1: subprocess.call(['sh',",
"GUI에서 사용자가 특정 파일 선택했다고 가정 n = int(input('Enter the minutes you want",
"에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0",
"range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as ex: branch =",
"except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice ==",
"5: path = \"./code/\" file_list = os.listdir(path) py_list = [file for file in",
"ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고",
"생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return ymd_ctime #",
"commit 실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh'])",
"while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을 기준으로",
"file_list if file.endswith(\".py\")] # c_list = [file for file in file_list if file.endswith(\".c\")]",
"commit하는 걸 백그라운드에서 실행 except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정",
"print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice",
"stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일 생성 시간) %",
"체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\")",
"ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을",
"'./continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else: print(\"Wrong Input! Please",
"세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼 해제되었다고",
"subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice =",
"# 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def stop():",
"'./addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch",
"= 0 while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time",
"= str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh'])",
"as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : # GUI에서 체크버튼",
"choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name",
"print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your",
"가정 print(ex) #if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif",
"filename = str(input(\"Enter your file name : \")) num = int(input('Enter the minutes",
"import datetime as dt import subprocess import time import os # auto commit",
"나머지 계산 def remainder(filename, start, stop, n): time_remainder = (stop - start(filename)) %",
"숫자로 바꾼 후, float형을 int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp =",
"choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh'])",
"schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create",
"'./continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file",
"print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을 기준으로 n분마다 auto commit하는",
"while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file)",
"subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter",
"mode\") print(\"5. Error Backup mode\") print(\"6. Git add file\") print(\"7. Git push to",
"remainder(filename, start, stop, n): time_remainder = (stop - start(filename)) % (60 * n)",
"the minutes you want to set up : ')) # GUI에서 사용자가 분을",
"elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name) \"))",
"체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice == 5: path = \"./code/\"",
"== 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh',",
"특정 파일 선택했다고 가정 n = int(input('Enter the minutes you want to set",
"except Exception as ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh',",
"autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가 실행될 때마다",
"backup mode\") print(\"4. Create time backup mode\") print(\"5. Error Backup mode\") print(\"6. Git",
"for i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as",
"elif choice == 5: path = \"./code/\" file_list = os.listdir(path) py_list = [file",
"ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후,",
"- subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice",
"ctime = os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를",
"auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file):",
"auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def",
"float형을 int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp",
"GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(),",
"후, float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return",
"(stop - start(filename)) % (60 * n) return time_remainder # 나머지가 0이 되면",
"')) # GUI에서 사용자가 특정 파일 선택했다고 가정 n = int(input('Enter the minutes",
"msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh'])",
"subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What",
"1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh'])",
"dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일 생성 시간)",
"ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을 기준으로 n분마다 auto commit하는 걸",
"# GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start,",
"subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name : ')) # GUI에서 사용자가",
"str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch,",
"변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로",
"# 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def start(filename):",
"choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name",
"for file in file_list if file.endswith(\".py\")] # c_list = [file for file in",
"str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif",
"choice = 0 while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3.",
"변환 def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을",
"(60 * n) return time_remainder # 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename,",
"계산 def remainder(filename, start, stop, n): time_remainder = (stop - start(filename)) % (60",
"# create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경",
"message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice ==",
"n): time_remainder = (stop - start(filename)) % (60 * n) return time_remainder #",
"time backup mode\") print(\"5. Error Backup mode\") print(\"6. Git add file\") print(\"7. Git",
"subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit message:",
"file name : \")) num = int(input('Enter the minutes you want to set",
"time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return ymd_ctime",
"주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice !=",
"% 60n을 통해서 나머지 계산 def remainder(filename, start, stop, n): time_remainder = (stop",
"in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception as ex: branch",
"def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file):",
"== 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name :",
"60n을 통해서 나머지 계산 def remainder(filename, start, stop, n): time_remainder = (stop -",
"up : ')) # GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except",
"int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice ==",
"import time import os # auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\")",
"add file\") print(\"7. Git push to branch\") print(\"8. Exit\") choice = int(input(\">> \"))",
"때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n)) # 나머지 출력 if remainder(filename,",
"# n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산",
"'./setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice",
"체크버튼 해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename",
"subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash',",
"choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg =",
"subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename",
"!= 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create",
"해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename =",
"os # auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh',",
"subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh'])",
"choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh'])",
"사용자가 분을 n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n)",
"print(\"시도\") time_based_autocommit(num) except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif",
"6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename])",
"subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice != 8: print(\"Menu\") print(\"1. New\")",
"나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice",
"want to set up : ')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정",
"'./setting.sh']) filename = str(input('Enter your file name : ')) # GUI에서 사용자가 특정",
"# GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice == 5: path",
"실행 - subprocess에서 에러가 계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\")",
"# 파일 생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception",
"except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if : #",
"os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성 ymd_ctime = dt.datetime.fromtimestamp(ctime) # 출력",
"def remainder(filename, start, stop, n): time_remainder = (stop - start(filename)) % (60 *",
"ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def",
"start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp # 현재시간을 timestamp를 이용해 float형 숫자로 바꾼 후,",
"universal_newlines=True) except Exception as ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh'])",
"msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh',",
"file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path + py_list[0]], universal_newlines=True) except Exception",
"')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True: try: print(\"시도\") ctime_based_autocommit(filename,",
"== 5: path = \"./code/\" file_list = os.listdir(path) py_list = [file for file",
"= str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh',",
"file_list = os.listdir(path) py_list = [file for file in file_list if file.endswith(\".py\")] #",
"가정 while True: try: print(\"시도\") ctime_based_autocommit(filename, start, stop(), n) # 파일 생성 시간을",
"time_remainder = (stop - start(filename)) % (60 * n) return time_remainder # 나머지가",
"파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def start(filename): start_time",
"바꾼 후, float형을 int형으로 변환 def stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp())",
"your file name : ')) # GUI에서 사용자가 특정 파일 선택했다고 가정 n",
"가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter",
"파일 생성 시간을 기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception as",
"auto commit하는 걸 백그라운드에서 실행 except Exception as ex: # GUI에서 체크버튼 해제되었다고",
"실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n)) # 나머지 출력 if",
"print(\"4. Create time backup mode\") print(\"5. Error Backup mode\") print(\"6. Git add file\")",
"선택했다고 가정 n = int(input('Enter the minutes you want to set up :",
"# 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n)) # 나머지",
"dt.datetime.fromtimestamp(ctime) # 출력 형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해",
"후, float형을 int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return",
"백그라운드에서 실행 except Exception as ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) #if",
"str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename =",
"print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename, start, stop, n))",
"want to set up : ')) # GUI에서 사용자가 분을 세팅했다고 가정 try:",
"# GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as ex:",
"'./autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name)",
"GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice == 5: path =",
"subprocess.call(['bash', './killProcess.sh']) filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh',",
"#if : # GUI에서 체크버튼 해제되었다고 가정 #print(\"버튼 해제2\") #break elif choice ==",
"stop(): stop_time = dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 -",
"실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if",
"'./killProcess.sh']) filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh'])",
"int형으로 변환 def start(filename): start_time = createtime(filename) start_time_timestamp = int(start_time.timestamp()) return start_time_timestamp #",
"subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while choice != 8:",
"print(\"6. Git add file\") print(\"7. Git push to branch\") print(\"8. Exit\") choice =",
"str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash',",
"- start(filename)) % (60 * n) return time_remainder # 나머지가 0이 되면 autocommit",
": ')) # GUI에서 사용자가 특정 파일 선택했다고 가정 n = int(input('Enter the",
"= str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 6: subprocess.call(['bash', './killProcess.sh']) filename",
"import threading import datetime as dt import subprocess import time import os #",
"사용자가 특정 파일 선택했다고 가정 n = int(input('Enter the minutes you want to",
"print(\"7. Git push to branch\") print(\"8. Exit\") choice = int(input(\">> \")) if choice",
"+ py_list[0]], universal_newlines=True) except Exception as ex: branch = str(\"error\") msg = str(ex)",
"이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환 def start(filename): start_time = createtime(filename)",
": ')) # GUI에서 사용자가 분을 n으로 세팅했다고 가정 while True: try: print(\"시도\")",
"가정 #print(\"버튼 해제2\") #break elif choice == 5: path = \"./code/\" file_list =",
"time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime",
"start, stop, n): print(\"시도 중\") # 함수가 실행될 때마다 '시도 중'을 출력 print(remainder(filename,",
"return time_remainder # 나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n):",
"start(filename)) % (60 * n) return time_remainder # 나머지가 0이 되면 autocommit 실행",
"0 while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\") print(\"3. Time backup",
"계속 나서 주석처리해놓음 subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) print(\"백업되었습니다.\") choice = 0 while",
"= dt.datetime.now() stop_time_timestamp = int(stop_time.timestamp()) return stop_time_timestamp # (현재 시간 - 파일 생성",
"to push?(branch_name) \")) msg = str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg])",
"filename = str(input(\"What file to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh',",
"#print(\"버튼 해제2\") #break elif choice == 5: path = \"./code/\" file_list = os.listdir(path)",
"ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice",
"print(\"2. Continue\") print(\"3. Time backup mode\") print(\"4. Create time backup mode\") print(\"5. Error",
"실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") # 함수가 실행될 때마다 '시도",
"')) # GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\") time_based_autocommit(num) except Exception as",
"format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을",
"print(\"백업되었습니다.\") choice = 0 while choice != 8: print(\"Menu\") print(\"1. New\") print(\"2. Continue\")",
"for file in file_list if file.endswith(\".java\")] for i in range(len(py_list)): try: subprocess.check_output(['python', path",
"subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice ==",
"to set up : ')) # GUI에서 사용자가 분을 세팅했다고 가정 try: print(\"시도\")",
"4: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input('Enter your file name : '))",
"stop, n): time_remainder = (stop - start(filename)) % (60 * n) return time_remainder",
"시간) % 60n을 통해서 나머지 계산 def remainder(filename, start, stop, n): time_remainder =",
"auto commit 실행 def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) #",
"subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1:",
"def auto_commit(): print(\"auto commit을 시행합니다\") subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행",
"형태를 ymd의 format으로 변경 return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼",
"기준으로 n분마다 auto commit하는 걸 백그라운드에서 실행 except Exception as ex: # GUI에서",
"str(input(\"Write commit message: \")) subprocess.call(['sh', './userCommit.sh', branch, msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif",
"- 파일 생성 시간) % 60n을 통해서 나머지 계산 def remainder(filename, start, stop,",
"msg]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 8: subprocess.call(['bash', './killProcess.sh']) else: print(\"Wrong",
"dt import subprocess import time import os # auto commit 실행 def auto_commit():",
"return ymd_ctime # 파일생성시간을 timestamp를 이용해 float형 숫자로 바꾼 후, float형을 int형으로 변환",
"== 3: subprocess.call(['bash', './killProcess.sh']) subprocess.call(['sh', './setting.sh']) filename = str(input(\"Enter your file name :",
"'./continue.sh']) subprocess.call(['sh', './TimeAutoCommitProcess.sh']) # n분마다 auto_commit 실행 def time_based_autocommit(num): schedule.every(num).minutes.do(auto_commit) while 1: schedule.run_pending()",
"file.endswith(\".c\")] # java_list = [file for file in file_list if file.endswith(\".java\")] for i",
"# 나머지 출력 if remainder(filename, start, stop, n) == 0: # auto commit",
"= [file for file in file_list if file.endswith(\".py\")] # c_list = [file for",
"you want to set up : ')) # GUI에서 사용자가 분을 세팅했다고 가정",
"ex: # GUI에서 체크버튼 해제되었다고 가정 print(ex) elif choice == 4: subprocess.call(['bash', './killProcess.sh'])",
"backup mode\") print(\"5. Error Backup mode\") print(\"6. Git add file\") print(\"7. Git push",
"py_list = [file for file in file_list if file.endswith(\".py\")] # c_list = [file",
"나머지가 0이 되면 autocommit 실행 def ctime_based_autocommit(filename, start, stop, n): print(\"시도 중\") #",
"Continue\") print(\"3. Time backup mode\") print(\"4. Create time backup mode\") print(\"5. Error Backup",
"통해서 나머지 계산 def remainder(filename, start, stop, n): time_remainder = (stop - start(filename))",
"to add?(file_name) \")) subprocess.call(['sh', './addFile.sh', filename]) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice ==",
"7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name) \")) msg = str(input(\"Write commit",
"== 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 2: subprocess.call(['sh', './continue.sh']) subprocess.call(['sh',",
"1: schedule.run_pending() # 파일생성시간을 계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) #",
"stop, n)) # 나머지 출력 if remainder(filename, start, stop, n) == 0: #",
"subprocess.call(['sh', './autoCommitProcess.sh']) elif choice == 7: subprocess.call(['bash', './killProcess.sh']) branch = str(input(\"Where to push?(branch_name)",
"print(\"8. Exit\") choice = int(input(\">> \")) if choice == 1: subprocess.call(['sh', './setting.sh']) subprocess.call(['sh',",
"계산 def createtime(file): if os.path.isfile(file): ctime = os.path.getctime(file) # create time 생성 ymd_ctime",
"as ex: branch = str(\"error\") msg = str(ex) subprocess.call(['sh', './continue.sh']) subprocess.call(['sh', './autoCommitProcess.sh']) elif"
] |
[
":param end: rank after the last rank. :return: list of document indices for",
"cosine similarity score for each document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j]",
"import numpy class CosineScore: \"\"\"Calculate cosine similarity score for each document and rank",
"query)) self.rank = list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number):",
"indices of the douments between the given ranks :param start: starting *rank*. :param",
"rankList # def main(): # query = [0, 1, 0] # matrix =",
"document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query))",
"> len(self.rank): min = len(self.rank) else: min = number for index in range(min):",
"numpy.array([[2, 1, 3], [4, 3, 5], [6, 5, 7]]) # obj = CosineScore(query,",
"them :param query: query vector :param matrix: tf-idf numpy matrix \"\"\" rank =",
"range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def main(): # query",
"of the douments between the given ranks :param start: starting *rank*. :param end:",
"document indices for ranks from start to end-1. \"\"\" rankList = [] if",
"number for index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList #",
"= [] self.docIndex = [] self.score = [] \"\"\"Constructor which calculates cosine similarity",
"matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x in",
"the last rank. :return: list of document indices for ranks from start to",
"len(self.rank): min = len(self.rank) else: min = number for index in range(min): if",
"which calculates cosine similarity score for each document\"\"\" for j in range(matrix.shape[1]): column",
"indices for ranks from start to end-1. \"\"\" rankList = [] if number",
"document and rank them :param query: query vector :param matrix: tf-idf numpy matrix",
"for each document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 -",
"0] # matrix = numpy.array([[2, 1, 3], [4, 3, 5], [6, 5, 7]])",
"of document indices for ranks from start to end-1. \"\"\" rankList = []",
"[4, 3, 5], [6, 5, 7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10))",
"len(self.rank) else: min = number for index in range(min): if self.score[self.rank[index]] > 0:",
"score for each document and rank them :param query: query vector :param matrix:",
"= len(self.rank) else: min = number for index in range(min): if self.score[self.rank[index]] >",
"# obj = CosineScore(query, matrix) # print(obj.getPages(10)) # # if __name__ == '__main__':",
"if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def main(): # query =",
"each document and rank them :param query: query vector :param matrix: tf-idf numpy",
"score = None def __init__(self, query, matrix): self.rank = [] self.docIndex = []",
"the indices of the douments between the given ranks :param start: starting *rank*.",
"get the indices of the douments between the given ranks :param start: starting",
"query = [0, 1, 0] # matrix = numpy.array([[2, 1, 3], [4, 3,",
"1, 0] # matrix = numpy.array([[2, 1, 3], [4, 3, 5], [6, 5,",
"from scipy import spatial import numpy class CosineScore: \"\"\"Calculate cosine similarity score for",
"for index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def",
"given ranks :param start: starting *rank*. :param end: rank after the last rank.",
"last rank. :return: list of document indices for ranks from start to end-1.",
"number > len(self.rank): min = len(self.rank) else: min = number for index in",
"# def main(): # query = [0, 1, 0] # matrix = numpy.array([[2,",
"\"\"\"Constructor which calculates cosine similarity score for each document\"\"\" for j in range(matrix.shape[1]):",
"_, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the indices of",
"self.docIndex))])) def getPages(self, number): \"\"\"To get the indices of the douments between the",
"score for each document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1",
":param query: query vector :param matrix: tf-idf numpy matrix \"\"\" rank = None",
"in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def main(): #",
"= numpy.array([[2, 1, 3], [4, 3, 5], [6, 5, 7]]) # obj =",
"matrix): self.rank = [] self.docIndex = [] self.score = [] \"\"\"Constructor which calculates",
"starting *rank*. :param end: rank after the last rank. :return: list of document",
"matrix = numpy.array([[2, 1, 3], [4, 3, 5], [6, 5, 7]]) # obj",
"\"\"\" rank = None docIndex = None score = None def __init__(self, query,",
"self.rank = [] self.docIndex = [] self.score = [] \"\"\"Constructor which calculates cosine",
"[] self.docIndex = [] self.score = [] \"\"\"Constructor which calculates cosine similarity score",
":return: list of document indices for ranks from start to end-1. \"\"\" rankList",
"matrix: tf-idf numpy matrix \"\"\" rank = None docIndex = None score =",
"[] self.score = [] \"\"\"Constructor which calculates cosine similarity score for each document\"\"\"",
"self.rank = list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To",
"ranks from start to end-1. \"\"\" rankList = [] if number > len(self.rank):",
"None score = None def __init__(self, query, matrix): self.rank = [] self.docIndex =",
"spatial import numpy class CosineScore: \"\"\"Calculate cosine similarity score for each document and",
"self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x in sorted(zip(self.score,",
"rankList = [] if number > len(self.rank): min = len(self.rank) else: min =",
"class CosineScore: \"\"\"Calculate cosine similarity score for each document and rank them :param",
"self.docIndex = [] self.score = [] \"\"\"Constructor which calculates cosine similarity score for",
"return rankList # def main(): # query = [0, 1, 0] # matrix",
"query, matrix): self.rank = [] self.docIndex = [] self.score = [] \"\"\"Constructor which",
"7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10)) # # if __name__ ==",
"def __init__(self, query, matrix): self.rank = [] self.docIndex = [] self.score = []",
"= None def __init__(self, query, matrix): self.rank = [] self.docIndex = [] self.score",
"end: rank after the last rank. :return: list of document indices for ranks",
"None docIndex = None score = None def __init__(self, query, matrix): self.rank =",
"spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self,",
"= None docIndex = None score = None def __init__(self, query, matrix): self.rank",
"the given ranks :param start: starting *rank*. :param end: rank after the last",
"for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the indices",
"for ranks from start to end-1. \"\"\" rankList = [] if number >",
"CosineScore: \"\"\"Calculate cosine similarity score for each document and rank them :param query:",
"# query = [0, 1, 0] # matrix = numpy.array([[2, 1, 3], [4,",
"5], [6, 5, 7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10)) # #",
"in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x",
"between the given ranks :param start: starting *rank*. :param end: rank after the",
"rankList.append(self.rank[index]) return rankList # def main(): # query = [0, 1, 0] #",
"min = len(self.rank) else: min = number for index in range(min): if self.score[self.rank[index]]",
"min = number for index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return",
":param matrix: tf-idf numpy matrix \"\"\" rank = None docIndex = None score",
"def getPages(self, number): \"\"\"To get the indices of the douments between the given",
"docIndex = None score = None def __init__(self, query, matrix): self.rank = []",
"each document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column,",
"for each document and rank them :param query: query vector :param matrix: tf-idf",
"end-1. \"\"\" rankList = [] if number > len(self.rank): min = len(self.rank) else:",
"douments between the given ranks :param start: starting *rank*. :param end: rank after",
"> 0: rankList.append(self.rank[index]) return rankList # def main(): # query = [0, 1,",
"None def __init__(self, query, matrix): self.rank = [] self.docIndex = [] self.score =",
"\"\"\"Calculate cosine similarity score for each document and rank them :param query: query",
"rank = None docIndex = None score = None def __init__(self, query, matrix):",
"__init__(self, query, matrix): self.rank = [] self.docIndex = [] self.score = [] \"\"\"Constructor",
"range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for",
"rank after the last rank. :return: list of document indices for ranks from",
"main(): # query = [0, 1, 0] # matrix = numpy.array([[2, 1, 3],",
"= [0, 1, 0] # matrix = numpy.array([[2, 1, 3], [4, 3, 5],",
"= CosineScore(query, matrix) # print(obj.getPages(10)) # # if __name__ == '__main__': # main()",
"number): \"\"\"To get the indices of the douments between the given ranks :param",
"query: query vector :param matrix: tf-idf numpy matrix \"\"\" rank = None docIndex",
"numpy class CosineScore: \"\"\"Calculate cosine similarity score for each document and rank them",
"import spatial import numpy class CosineScore: \"\"\"Calculate cosine similarity score for each document",
"3], [4, 3, 5], [6, 5, 7]]) # obj = CosineScore(query, matrix) #",
"getPages(self, number): \"\"\"To get the indices of the douments between the given ranks",
"rank them :param query: query vector :param matrix: tf-idf numpy matrix \"\"\" rank",
"query vector :param matrix: tf-idf numpy matrix \"\"\" rank = None docIndex =",
"from start to end-1. \"\"\" rankList = [] if number > len(self.rank): min",
"self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def main(): # query = [0,",
"1, 3], [4, 3, 5], [6, 5, 7]]) # obj = CosineScore(query, matrix)",
"def main(): # query = [0, 1, 0] # matrix = numpy.array([[2, 1,",
"if number > len(self.rank): min = len(self.rank) else: min = number for index",
"*rank*. :param end: rank after the last rank. :return: list of document indices",
"sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the indices of the douments between",
"for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank",
"\"\"\"To get the indices of the douments between the given ranks :param start:",
"# matrix = numpy.array([[2, 1, 3], [4, 3, 5], [6, 5, 7]]) #",
"the douments between the given ranks :param start: starting *rank*. :param end: rank",
"self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))]))",
"vector :param matrix: tf-idf numpy matrix \"\"\" rank = None docIndex = None",
"else: min = number for index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index])",
"similarity score for each document and rank them :param query: query vector :param",
"start to end-1. \"\"\" rankList = [] if number > len(self.rank): min =",
"cosine similarity score for each document and rank them :param query: query vector",
"j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank =",
"start: starting *rank*. :param end: rank after the last rank. :return: list of",
"after the last rank. :return: list of document indices for ranks from start",
"= list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get",
"matrix \"\"\" rank = None docIndex = None score = None def __init__(self,",
"[] if number > len(self.rank): min = len(self.rank) else: min = number for",
"list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the",
"ranks :param start: starting *rank*. :param end: rank after the last rank. :return:",
"= [] if number > len(self.rank): min = len(self.rank) else: min = number",
"numpy matrix \"\"\" rank = None docIndex = None score = None def",
"rank. :return: list of document indices for ranks from start to end-1. \"\"\"",
"[] \"\"\"Constructor which calculates cosine similarity score for each document\"\"\" for j in",
"[6, 5, 7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10)) # # if",
"= number for index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList",
"self.score = [] \"\"\"Constructor which calculates cosine similarity score for each document\"\"\" for",
"column = matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _,",
"5, 7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10)) # # if __name__",
"similarity score for each document\"\"\" for j in range(matrix.shape[1]): column = matrix[:,j] self.docIndex.append(j)",
"0: rankList.append(self.rank[index]) return rankList # def main(): # query = [0, 1, 0]",
"= [] self.score = [] \"\"\"Constructor which calculates cosine similarity score for each",
"= matrix[:,j] self.docIndex.append(j) self.score.append(1 - spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x",
"<reponame>Robo-Sapien/Search-Engine-for-arXiv.org from scipy import spatial import numpy class CosineScore: \"\"\"Calculate cosine similarity score",
"calculates cosine similarity score for each document\"\"\" for j in range(matrix.shape[1]): column =",
"and rank them :param query: query vector :param matrix: tf-idf numpy matrix \"\"\"",
"= None score = None def __init__(self, query, matrix): self.rank = [] self.docIndex",
"\"\"\" rankList = [] if number > len(self.rank): min = len(self.rank) else: min",
"x in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the indices of the",
"index in range(min): if self.score[self.rank[index]] > 0: rankList.append(self.rank[index]) return rankList # def main():",
"3, 5], [6, 5, 7]]) # obj = CosineScore(query, matrix) # print(obj.getPages(10)) #",
"list of document indices for ranks from start to end-1. \"\"\" rankList =",
"to end-1. \"\"\" rankList = [] if number > len(self.rank): min = len(self.rank)",
"= [] \"\"\"Constructor which calculates cosine similarity score for each document\"\"\" for j",
"in sorted(zip(self.score, self.docIndex))])) def getPages(self, number): \"\"\"To get the indices of the douments",
"obj = CosineScore(query, matrix) # print(obj.getPages(10)) # # if __name__ == '__main__': #",
"scipy import spatial import numpy class CosineScore: \"\"\"Calculate cosine similarity score for each",
"[0, 1, 0] # matrix = numpy.array([[2, 1, 3], [4, 3, 5], [6,",
"tf-idf numpy matrix \"\"\" rank = None docIndex = None score = None",
"- spatial.distance.cosine(column, query)) self.rank = list(reversed([x for _, x in sorted(zip(self.score, self.docIndex))])) def",
":param start: starting *rank*. :param end: rank after the last rank. :return: list"
] |
[
"url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json() if __name__ ==",
"response = requests.get(url + search_city) return response.json() if __name__ == \"__main__\": args =",
"f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json() if __name__ == \"__main__\": args",
"args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\") except",
"weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you",
"metavar=\"my_city\", type=str, help=\"City for which you want to get weather.\" ) def get_city_weather(search_city):",
"description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which",
"you want to get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url =",
"get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response =",
"get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return",
"arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\") except KeyError: print(\"City",
"want to get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\"",
"city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you want to get",
"prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for",
"entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you want to",
"argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City",
"weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url",
"type=str, help=\"City for which you want to get weather.\" ) def get_city_weather(search_city): api_key",
"to get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response",
"help=\"City for which you want to get weather.\" ) def get_city_weather(search_city): api_key =",
"== \"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}:",
"= arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\") except KeyError:",
"arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\",",
"python import argparse import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered",
"which you want to get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url",
"api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json()",
"requests.get(url + search_city) return response.json() if __name__ == \"__main__\": args = arg_parser.parse_args() try:",
") def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url +",
"argparse import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" )",
"import argparse import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\"",
") arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you want to get weather.\"",
"arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you want to get weather.\" )",
"\"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json() if __name__",
"if __name__ == \"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather",
"= \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json() if",
"try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\") except KeyError: print(\"City no",
"requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\",",
"weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\") except KeyError: print(\"City no found.\")",
"def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\" url = f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city)",
"import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument(",
"#! /usr/bin/env python import argparse import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather",
"for which you want to get weather.\" ) def get_city_weather(search_city): api_key = \"2fe992c00735713d86f2d6577ff41a3d\"",
"search_city) return response.json() if __name__ == \"__main__\": args = arg_parser.parse_args() try: weather =",
"= f\"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q=\" response = requests.get(url + search_city) return response.json() if __name__ == \"__main__\":",
"+ search_city) return response.json() if __name__ == \"__main__\": args = arg_parser.parse_args() try: weather",
"\"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in {args.city}: {weather['weather'][0]['description']}\")",
"for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str, help=\"City for which you want",
"/usr/bin/env python import argparse import requests arg_parser = argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for",
"= argparse.ArgumentParser( prog=\"get-weather\", description=\"Get weather for entered city.\" ) arg_parser.add_argument( \"city\", metavar=\"my_city\", type=str,",
"\"city\", metavar=\"my_city\", type=str, help=\"City for which you want to get weather.\" ) def",
"__name__ == \"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The weather in",
"response.json() if __name__ == \"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city) print(f\"The",
"= requests.get(url + search_city) return response.json() if __name__ == \"__main__\": args = arg_parser.parse_args()",
"return response.json() if __name__ == \"__main__\": args = arg_parser.parse_args() try: weather = get_city_weather(args.city)"
] |
[
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations",
"by Django 3.0.7 on 2020-06-14 15:47 import django.core.validators from django.db import migrations, models",
"= [ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField( model_name='urlmapping', name='original_url', field=models.TextField(validators=[django.core.validators.URLValidator]), ),",
"2020-06-14 15:47 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"3.0.7 on 2020-06-14 15:47 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration):",
"django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'),",
"[ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField( model_name='urlmapping', name='original_url', field=models.TextField(validators=[django.core.validators.URLValidator]), ), ]",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ]",
"# Generated by Django 3.0.7 on 2020-06-14 15:47 import django.core.validators from django.db import",
"class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField( model_name='urlmapping',",
"on 2020-06-14 15:47 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations =",
"import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main',",
"Generated by Django 3.0.7 on 2020-06-14 15:47 import django.core.validators from django.db import migrations,",
"dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField( model_name='urlmapping', name='original_url', field=models.TextField(validators=[django.core.validators.URLValidator]),",
"15:47 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations = [",
"Django 3.0.7 on 2020-06-14 15:47 import django.core.validators from django.db import migrations, models class",
"models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField(",
"Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200614_1506'), ] operations = [ migrations.AlterField( model_name='urlmapping', name='original_url',"
] |
[
"= (screen_width, screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal = True def",
"def act(self, action): accumulated_reward = 0 start_lives = self.lives self.step(action) if start_lives >",
"255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property",
"self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal",
"super(GymEnvironment, self).__init__(config) self.config = config def act(self, action): accumulated_reward = 0 start_lives =",
"self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def act(self,",
"self.reward = 0 self.terminal = True def new_game(self): self._screen = self.env.reset() self.render() return",
"0, self.terminal def step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self):",
"self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def",
"= self.lives self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward -= self.config.max_punishment self.render()",
"self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal = True",
".utils import rgb2gray, imresize class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width,",
"return self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self,",
"0, 0, self.terminal def step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def",
"0 self.terminal = True def new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0,",
"self.render() return self.screen, 0, 0, self.terminal def step(self, action): self._screen, self.reward, self.terminal, _",
"action): accumulated_reward = 0 start_lives = self.lives self.step(action) if start_lives > self.lives and",
"class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def act(self, action):",
"class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height",
"self._screen = self.env.reset() self.reward = 0 self.terminal = True def new_game(self): self._screen =",
"self.lives self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward -= self.config.max_punishment self.render() return",
"@property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0]",
"return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self):",
"def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config",
"accumulated_reward = 0 start_lives = self.lives self.step(action) if start_lives > self.lives and self.terminal:",
"self.terminal def step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action",
"= config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset()",
"@property def lives(self): return self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal def",
"screen_height = config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width, screen_height) self._screen =",
"self.terminal, _ = self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self):",
"config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal =",
"gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width, screen_height)",
"return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def lives(self): return",
"self.screen, 0, 0, self.terminal def step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action)",
"if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config",
"imresize class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width,",
"render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config =",
"True def new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0, 0, self.terminal def",
"= gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width,",
"config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display self.dims",
"def action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def state(self): return",
"self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property",
"self).__init__(config) self.config = config def act(self, action): accumulated_reward = 0 start_lives = self.lives",
"= config def act(self, action): accumulated_reward = 0 start_lives = self.lives self.step(action) if",
"0 start_lives = self.lives self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward -=",
"config.screen_height self.display = config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward =",
"return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def state(self): return self.screen, self.reward,",
"act(self, action): accumulated_reward = 0 start_lives = self.lives self.step(action) if start_lives > self.lives",
"self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen,",
"from .utils import rgb2gray, imresize class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name)",
"self.display = config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward = 0",
"import rgb2gray, imresize class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height",
"self.reward, self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment,",
"def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def act(self, action): accumulated_reward =",
"self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render()",
"self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config):",
"def random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255.,",
"= config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal",
"self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property def",
"(screen_width, screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal = True def new_game(self):",
"GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def act(self, action): accumulated_reward",
"state(self): return self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def",
"self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255.,",
"screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def",
"new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0, 0, self.terminal def step(self, action):",
"self.config = config def act(self, action): accumulated_reward = 0 start_lives = self.lives self.step(action)",
"rgb2gray, imresize class Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height =",
"<filename>dqn/environment.py<gh_stars>1-10 import gym from .utils import rgb2gray, imresize class Environment(object): def __init__(self, config):",
"imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return",
"= self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return",
"= self.env.reset() self.render() return self.screen, 0, 0, self.terminal def step(self, action): self._screen, self.reward,",
"self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def",
"= 0 self.terminal = True def new_game(self): self._screen = self.env.reset() self.render() return self.screen,",
"= 0 start_lives = self.lives self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward",
"self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config)",
"config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width, screen_height) self._screen = self.env.reset() self.reward",
"step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action = self.env.action_space.sample()",
"cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property",
"self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward -= self.config.max_punishment self.render() return self.state",
"= self.env.reset() self.reward = 0 self.terminal = True def new_game(self): self._screen = self.env.reset()",
"self.env.reset() self.render() return self.screen, 0, 0, self.terminal def step(self, action): self._screen, self.reward, self.terminal,",
"def new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0, 0, self.terminal def step(self,",
"action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def state(self): return self.screen,",
"@property def action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives() @property def state(self):",
"config def act(self, action): accumulated_reward = 0 start_lives = self.lives self.step(action) if start_lives",
"self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display self.dims =",
"def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display =",
"self.display: self.env.render() class GymEnvironment(Environment): def __init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def",
"__init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display",
"screen_width, screen_height = config.screen_width, config.screen_height self.display = config.display self.dims = (screen_width, screen_height) self._screen",
"Environment(object): def __init__(self, config): self.env = gym.make(config.env_name) screen_width, screen_height = config.screen_width, config.screen_height self.display",
"config): super(GymEnvironment, self).__init__(config) self.config = config def act(self, action): accumulated_reward = 0 start_lives",
"@property def state(self): return self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render() class",
"/ 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n",
"random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims)",
"return self.screen, 0, 0, self.terminal def step(self, action): self._screen, self.reward, self.terminal, _ =",
"_ = self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self): return",
"= True def new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0, 0, self.terminal",
"return self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal def render(self): if self.display:",
"gym from .utils import rgb2gray, imresize class Environment(object): def __init__(self, config): self.env =",
"self._screen = self.env.reset() self.render() return self.screen, 0, 0, self.terminal def step(self, action): self._screen,",
"self.env.reset() self.reward = 0 self.terminal = True def new_game(self): self._screen = self.env.reset() self.render()",
"# return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def lives(self):",
"= self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen)",
"lives(self): return self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal def render(self): if",
"def state(self): return self.screen, self.reward, self.terminal def render(self): if self.display: self.env.render() class GymEnvironment(Environment):",
"def step(self, action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action =",
"__init__(self, config): super(GymEnvironment, self).__init__(config) self.config = config def act(self, action): accumulated_reward = 0",
"def lives(self): return self.env.ale.lives() @property def state(self): return self.screen, self.reward, self.terminal def render(self):",
"def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) # return cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property",
"cv2.resize(cv2.cvtColor(self._screen, cv2.COLOR_BGR2YCR_CB)/255., self.dims)[:,:,0] @property def action_size(self): return self.env.action_space.n @property def lives(self): return self.env.ale.lives()",
"action = self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) / 255., self.dims) #",
"self.terminal = True def new_game(self): self._screen = self.env.reset() self.render() return self.screen, 0, 0,",
"import gym from .utils import rgb2gray, imresize class Environment(object): def __init__(self, config): self.env",
"screen_height) self._screen = self.env.reset() self.reward = 0 self.terminal = True def new_game(self): self._screen",
"action): self._screen, self.reward, self.terminal, _ = self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action)",
"self.env.step(action) def random_step(self): action = self.env.action_space.sample() self.step(action) @property def screen(self): return imresize(rgb2gray(self._screen) /",
"start_lives = self.lives self.step(action) if start_lives > self.lives and self.terminal: accumulated_reward -= self.config.max_punishment"
] |
[
"from django.core.management.utils import get_random_secret_key secret_key = get_random_secret_key() text = 'SECRET_KEY = \\'{0}\\''.format(secret_key) print(text)"
] |
[] |
[
"return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface",
"level of hypernyms to the master bag of tokens for hypernym in nextStack:",
"add the enriched bag of words as value to current d expandedText.append(expandedTokens) data.append(idea)",
"in ideas: # read the text text = idea['content'].encode('utf-8', 'ignore') # split into",
"convert treebank tags into wordnet pos tags for query expansion \"\"\" if treebank_tag.startswith('J'):",
"the synonyms bowTokens = set([t[0] for t in pos_tokens]) for synonym in synonyms:",
"words (TreeBank) pos_tokens = [] for sentence in sentences: tokens = [token.lower() for",
"and hypernyms for each token in input list of token-posTag tuples return expanded",
"s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the",
"import nltk from nltk.corpus import wordnet as wn import numpy as np from",
"tuples return expanded list of tokens that includes synonyms and hypernyms \"\"\" #",
"synonyms and hypernyms for each token in input list of token-posTag tuples return",
"in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag # remove stopwords",
"return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for Mike Terri's",
"wordnet to recursively add all synonyms and hypernyms for each token in input",
"= set(nextStack) nextStack.clear() # get all hypernyms, put in nextStack for s in",
"else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags into",
"import numpy as np from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1",
"mag1 and mag2: return dotProduct / (mag1 * mag2) else: return 0.0 def",
"input list of token-posTag tuples return expanded list of tokens that includes synonyms",
"# Author: <NAME> <EMAIL> import nltk from nltk.corpus import wordnet as wn import",
"tag # remove stopwords pos_tokens = [t for t in pos_tokens if t[0]",
"for Mike Terri's Ideaforest algorithm \"\"\" expandedText = [] data = [] for",
"= [t for t in pos_tokens if t[0] not in stopwords] # remove",
"= nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank) pos_tokens = [] for",
"[] for sentence in sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)] #",
"mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in",
"pos_tokens]) for synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively",
"wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start making the list of",
"= wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start making the list",
"\"\"\" helper method to convert treebank tags into wordnet pos tags for query",
"nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens",
"<reponame>stevencdang/data_proc_lib<filename>nlp/nlp.py #!/usr/bin/env python # Author: <NAME> <EMAIL> import nltk from nltk.corpus import wordnet",
"def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1,",
"in t[0])] # query expansion expandedTokens = expand_text(pos_tokens) # add the enriched bag",
"initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all hypernyms, put in",
"\"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for Mike",
"# now recursively add hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack",
"expand_text(pos_tokens) # add the enriched bag of words as value to current d",
"pos_tokens = [t for t in pos_tokens if any(c.isalpha() for c in t[0])]",
"all synonyms and hypernyms for each token in input list of token-posTag tuples",
"pos_tokens = [] for sentence in sentences: tokens = [token.lower() for token in",
"wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface with",
"pos_tokens = [t for t in pos_tokens if t[0] not in stopwords] #",
"tokenize and pos tag words (TreeBank) pos_tokens = [] for sentence in sentences:",
"# read the text text = idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer)",
"(mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert",
"start making the list of tokens to be output # initialize with lemmas",
"elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else:",
"nltk.corpus import wordnet as wn import numpy as np from file_manager import read_data",
"of stop words. Currently uses a list of words in a text file",
"hypernyms for each token in input list of token-posTag tuples return expanded list",
"while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all hypernyms, put in nextStack for",
"# add lemmas from the current level of hypernyms to the master bag",
"in pos_tokens]) for synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now",
"if mag1 and mag2: return dotProduct / (mag1 * mag2) else: return 0.0",
"doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight",
"stop words. Currently uses a list of words in a text file \"\"\"",
"'' def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add all synonyms and",
"get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start making the list of tokens",
"remove stopwords pos_tokens = [t for t in pos_tokens if t[0] not in",
"Ideaforest algorithm \"\"\" expandedText = [] data = [] for idea in ideas:",
"in pos_tokens if any(c.isalpha() for c in t[0])] # query expansion expandedTokens =",
"read the text text = idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences",
"in input list of token-posTag tuples return expanded list of tokens that includes",
"query expansion expandedTokens = expand_text(pos_tokens) # add the enriched bag of words as",
"processing of ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText = [] data",
"the current level of hypernyms to the master bag of tokens for hypernym",
"get_stopwords(): \"\"\" Returns a list of stop words. Currently uses a list of",
"hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current level of hypernyms",
"wordnet pos tags for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'):",
"synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start making the",
"lemmas from the current level of hypernyms to the master bag of tokens",
"hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\"",
"t in pos_tokens if t[0] not in stopwords] # remove \"words\" with no",
"wordnet as wn import numpy as np from file_manager import read_data def cosine(doc1,",
"for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset)",
"words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial",
"weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and",
"for idea in ideas: # read the text text = idea['content'].encode('utf-8', 'ignore') #",
"in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack = set(synonyms) # initialize",
"uses a list of words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def",
"in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack",
"return dotProduct / (mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper",
"to the master bag of tokens for hypernym in nextStack: for lemma in",
"remove \"words\" with no letters in them! pos_tokens = [t for t in",
"synsets: synonyms.add(synset) # start making the list of tokens to be output #",
"initialize with lemmas of the synonyms bowTokens = set([t[0] for t in pos_tokens])",
"text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas",
"return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return",
"synset in synsets: synonyms.add(synset) # start making the list of tokens to be",
"get all hypernyms, put in nextStack for s in currentStack: for hypernym in",
"wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add",
"synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack = set(synonyms) # initialize stack",
"split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos tag words",
"mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and mag2: return dotProduct",
"return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return ''",
"expandedText = [] data = [] for idea in ideas: # read the",
"in stopwords] # remove \"words\" with no letters in them! pos_tokens = [t",
"stopwords] # remove \"words\" with no letters in them! pos_tokens = [t for",
"python # Author: <NAME> <EMAIL> import nltk from nltk.corpus import wordnet as wn",
"def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for Mike Terri's Ideaforest algorithm",
"= np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight)",
"pos tags for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return",
"= [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos",
"Initial processing of ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText = []",
"words. Currently uses a list of words in a text file \"\"\" return",
"= np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2]))",
"doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2",
"nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get",
"expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add all synonyms and hypernyms for",
"def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags into wordnet pos tags",
"for hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords():",
"wn import numpy as np from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights):",
"hypernyms, put in nextStack for s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym)",
"ideas: # read the text text = idea['content'].encode('utf-8', 'ignore') # split into sentences",
"Terri's Ideaforest algorithm \"\"\" expandedText = [] data = [] for idea in",
"expansion expandedTokens = expand_text(pos_tokens) # add the enriched bag of words as value",
"= [] data = [] for idea in ideas: # read the text",
"for t in pos_tokens if t[0] not in stopwords] # remove \"words\" with",
"of tokens that includes synonyms and hypernyms \"\"\" # first expand with synonyms",
"item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) #",
"set([t[0] for t in pos_tokens]) for synonym in synonyms: for lemma in synonym.lemmas():",
"nextStack for s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas",
"wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV",
"recursively add all synonyms and hypernyms for each token in input list of",
"= [] for sentence in sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)]",
"pos tag words (TreeBank) pos_tokens = [] for sentence in sentences: tokens =",
"<EMAIL> import nltk from nltk.corpus import wordnet as wn import numpy as np",
"Returns a list of stop words. Currently uses a list of words in",
"for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list",
"t in pos_tokens]) for synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) #",
"0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags into wordnet pos",
"of hypernyms to the master bag of tokens for hypernym in nextStack: for",
"from the current level of hypernyms to the master bag of tokens for",
"wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return '' def",
"weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight",
"for weight in weights2])) if mag1 and mag2: return dotProduct / (mag1 *",
"a list of words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas,",
"expanded list of tokens that includes synonyms and hypernyms \"\"\" # first expand",
"helper method to convert treebank tags into wordnet pos tags for query expansion",
"now recursively add hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack =",
"into wordnet pos tags for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif",
"hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() #",
"sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens)",
"a list of stop words. Currently uses a list of words in a",
"= doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1]))",
"treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return",
"# add the enriched bag of words as value to current d expandedText.append(expandedTokens)",
"treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface with wordnet to",
"# first expand with synonyms synonyms = set() for item in pos_tokens: synsets",
"to convert treebank tags into wordnet pos tags for query expansion \"\"\" if",
"the enriched bag of words as value to current d expandedText.append(expandedTokens) data.append(idea) return",
"currentStack = set(nextStack) nextStack.clear() # get all hypernyms, put in nextStack for s",
"the text text = idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences =",
"ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText = [] data = []",
"lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack = set(synonyms) #",
"[token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag",
"'ignore') # split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos",
"= set() for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in",
"in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of stop",
"a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of",
"dotProduct / (mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method",
"get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags into wordnet pos tags for",
"that includes synonyms and hypernyms \"\"\" # first expand with synonyms synonyms =",
"read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct =",
"synonyms bowTokens = set([t[0] for t in pos_tokens]) for synonym in synonyms: for",
"tokens that includes synonyms and hypernyms \"\"\" # first expand with synonyms synonyms",
"# get all hypernyms, put in nextStack for s in currentStack: for hypernym",
"data = [] for idea in ideas: # read the text text =",
"synonyms.add(synset) # start making the list of tokens to be output # initialize",
"as np from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1]",
"output # initialize with lemmas of the synonyms bowTokens = set([t[0] for t",
"# split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos tag",
"(TreeBank) pos_tokens = [] for sentence in sentences: tokens = [token.lower() for token",
"of token-posTag tuples return expanded list of tokens that includes synonyms and hypernyms",
"making the list of tokens to be output # initialize with lemmas of",
"for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag #",
"with no letters in them! pos_tokens = [t for t in pos_tokens if",
"def get_stopwords(): \"\"\" Returns a list of stop words. Currently uses a list",
"with wordnet to recursively add all synonyms and hypernyms for each token in",
"nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank) pos_tokens = [] for sentence",
"nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens = [t for t in",
"import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct",
"includes synonyms and hypernyms \"\"\" # first expand with synonyms synonyms = set()",
"np from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2",
"the list of tokens to be output # initialize with lemmas of the",
"expand with synonyms synonyms = set() for item in pos_tokens: synsets = wn.synsets(item[0],",
"set() for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets:",
"synonyms and hypernyms \"\"\" # first expand with synonyms synonyms = set() for",
"stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all hypernyms, put in nextStack",
"hypernyms \"\"\" # first expand with synonyms synonyms = set() for item in",
"in them! pos_tokens = [t for t in pos_tokens if any(c.isalpha() for c",
"bag of tokens for hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return",
"+= nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens = [t for t",
"query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'):",
"return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively",
"synonyms synonyms = set() for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for",
"master bag of tokens for hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name())",
"tags into wordnet pos tags for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ",
"nextStack.clear() # get all hypernyms, put in nextStack for s in currentStack: for",
"sentences = nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank) pos_tokens = []",
"in synsets: synonyms.add(synset) # start making the list of tokens to be output",
"method to convert treebank tags into wordnet pos tags for query expansion \"\"\"",
"# pos tag # remove stopwords pos_tokens = [t for t in pos_tokens",
"treebank tags into wordnet pos tags for query expansion \"\"\" if treebank_tag.startswith('J'): return",
"doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 =",
"tokens = [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) #",
"expandedTokens = expand_text(pos_tokens) # add the enriched bag of words as value to",
"nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a",
"idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and",
"token-posTag tuples return expanded list of tokens that includes synonyms and hypernyms \"\"\"",
"hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of stop words.",
"weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in",
"and mag2: return dotProduct / (mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag):",
"to be output # initialize with lemmas of the synonyms bowTokens = set([t[0]",
"for t in pos_tokens]) for synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name())",
"not in stopwords] # remove \"words\" with no letters in them! pos_tokens =",
"list of tokens that includes synonyms and hypernyms \"\"\" # first expand with",
"c in t[0])] # query expansion expandedTokens = expand_text(pos_tokens) # add the enriched",
"/ (mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to",
"interface with wordnet to recursively add all synonyms and hypernyms for each token",
"np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for",
"read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for Mike Terri's Ideaforest",
"as wn import numpy as np from file_manager import read_data def cosine(doc1, doc2,",
"[] for idea in ideas: # read the text text = idea['content'].encode('utf-8', 'ignore')",
"the master bag of tokens for hypernym in nextStack: for lemma in hypernym.lemmas():",
"and hypernyms \"\"\" # first expand with synonyms synonyms = set() for item",
"be output # initialize with lemmas of the synonyms bowTokens = set([t[0] for",
"all hypernyms, put in nextStack for s in currentStack: for hypernym in s.hypernyms():",
"nltk from nltk.corpus import wordnet as wn import numpy as np from file_manager",
"weight in weights2])) if mag1 and mag2: return dotProduct / (mag1 * mag2)",
"text = idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) #",
"t[0])] # query expansion expandedTokens = expand_text(pos_tokens) # add the enriched bag of",
"np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and mag2: return dotProduct / (mag1",
"bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for Mike Terri's Ideaforest algorithm \"\"\"",
"tag words (TreeBank) pos_tokens = [] for sentence in sentences: tokens = [token.lower()",
"add lemmas from the current level of hypernyms to the master bag of",
"if t[0] not in stopwords] # remove \"words\" with no letters in them!",
"Currently uses a list of words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\")",
"t in pos_tokens if any(c.isalpha() for c in t[0])] # query expansion expandedTokens",
"pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start making",
"\"\"\" # first expand with synonyms synonyms = set() for item in pos_tokens:",
"of words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\"",
"import wordnet as wn import numpy as np from file_manager import read_data def",
"\"words\" with no letters in them! pos_tokens = [t for t in pos_tokens",
"current level of hypernyms to the master bag of tokens for hypernym in",
"[t for t in pos_tokens if t[0] not in stopwords] # remove \"words\"",
"# tokenize and pos tag words (TreeBank) pos_tokens = [] for sentence in",
"\"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN",
"set(nextStack) nextStack.clear() # get all hypernyms, put in nextStack for s in currentStack:",
"= [t for t in pos_tokens if any(c.isalpha() for c in t[0])] #",
"pos_tokens if any(c.isalpha() for c in t[0])] # query expansion expandedTokens = expand_text(pos_tokens)",
"elif treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\" interface with wordnet",
"idea in ideas: # read the text text = idea['content'].encode('utf-8', 'ignore') # split",
"bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)):",
"<NAME> <EMAIL> import nltk from nltk.corpus import wordnet as wn import numpy as",
"lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of",
"in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current level of hypernyms to",
"= idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize",
"add hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear()",
"for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current level of",
"treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens): \"\"\"",
"hypernyms to the master bag of tokens for hypernym in nextStack: for lemma",
"in sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens +=",
"[] data = [] for idea in ideas: # read the text text",
"= np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and mag2: return dotProduct /",
"for c in t[0])] # query expansion expandedTokens = expand_text(pos_tokens) # add the",
"them! pos_tokens = [t for t in pos_tokens if any(c.isalpha() for c in",
"and pos tag words (TreeBank) pos_tokens = [] for sentence in sentences: tokens",
"of ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText = [] data =",
"pos_tokens += nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens = [t for",
"(PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank) pos_tokens =",
"= set([t[0] for t in pos_tokens]) for synonym in synonyms: for lemma in",
"Mike Terri's Ideaforest algorithm \"\"\" expandedText = [] data = [] for idea",
"pos tag # remove stopwords pos_tokens = [t for t in pos_tokens if",
"in weights2])) if mag1 and mag2: return dotProduct / (mag1 * mag2) else:",
"for s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from",
"bowTokens = set([t[0] for t in pos_tokens]) for synonym in synonyms: for lemma",
"if any(c.isalpha() for c in t[0])] # query expansion expandedTokens = expand_text(pos_tokens) #",
"mag2: return dotProduct / (mag1 * mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\"",
"if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif",
"# remove \"words\" with no letters in them! pos_tokens = [t for t",
"synonyms = set() for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset",
"# initialize with lemmas of the synonyms bowTokens = set([t[0] for t in",
"for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif",
"token in input list of token-posTag tuples return expanded list of tokens that",
"algorithm \"\"\" expandedText = [] data = [] for idea in ideas: #",
"return expanded list of tokens that includes synonyms and hypernyms \"\"\" # first",
"stopwords): \"\"\" Initial processing of ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText",
"else: return '' def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add all",
"np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if",
"dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for weight in weights1])) mag2 =",
"no letters in them! pos_tokens = [t for t in pos_tokens if any(c.isalpha()",
"cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2)",
"currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current level",
"return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of stop words. Currently uses",
"for weight in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1",
"in nextStack for s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add",
"enriched bag of words as value to current d expandedText.append(expandedTokens) data.append(idea) return data,",
"= doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight) for",
"s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current level of hypernyms to the",
"in weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and mag2:",
"# remove stopwords pos_tokens = [t for t in pos_tokens if t[0] not",
"letters in them! pos_tokens = [t for t in pos_tokens if any(c.isalpha() for",
"expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return",
"from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 =",
"= set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all",
"into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank)",
"each token in input list of token-posTag tuples return expanded list of tokens",
"file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing of ideas for",
"of the synonyms bowTokens = set([t[0] for t in pos_tokens]) for synonym in",
"return '' def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add all synonyms",
"sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of stop words. Currently uses a",
"file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2]",
"# start making the list of tokens to be output # initialize with",
"synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack =",
"= expand_text(pos_tokens) # add the enriched bag of words as value to current",
"bag of words as value to current d expandedText.append(expandedTokens) data.append(idea) return data, expandedText",
"\"\"\" interface with wordnet to recursively add all synonyms and hypernyms for each",
"weights1])) mag2 = np.sqrt(sum([np.square(weight) for weight in weights2])) if mag1 and mag2: return",
"with lemmas of the synonyms bowTokens = set([t[0] for t in pos_tokens]) for",
"for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms nextStack = set(synonyms)",
"# initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all hypernyms, put",
"treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'):",
"token in nltk.word_tokenize(sentence)] # tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag # remove",
"return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags into wordnet",
"of tokens to be output # initialize with lemmas of the synonyms bowTokens",
"sentence in sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize pos_tokens",
"elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('R'): return wn.ADV else: return '' def expand_text(pos_tokens):",
"= [] for idea in ideas: # read the text text = idea['content'].encode('utf-8',",
"in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1])) for synset in synsets: synonyms.add(synset) # start",
"stopwords pos_tokens = [t for t in pos_tokens if t[0] not in stopwords]",
"first expand with synonyms synonyms = set() for item in pos_tokens: synsets =",
"to recursively add all synonyms and hypernyms for each token in input list",
"tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens = [t",
"[t for t in pos_tokens if any(c.isalpha() for c in t[0])] # query",
"for synset in synsets: synonyms.add(synset) # start making the list of tokens to",
"for each token in input list of token-posTag tuples return expanded list of",
"for sentence in sentences: tokens = [token.lower() for token in nltk.word_tokenize(sentence)] # tokenize",
"doc2, doc_topic_weights): weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1",
"tags for query expansion \"\"\" if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB",
"weights1 = doc_topic_weights[doc1] weights2 = doc_topic_weights[doc2] dotProduct = np.dot(weights1, weights2) mag1 = np.sqrt(sum([np.square(weight)",
"mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank tags",
"tokens for hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def",
"pos_tokens if t[0] not in stopwords] # remove \"words\" with no letters in",
"set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack) nextStack.clear() # get all hypernyms,",
"synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add hypernyms",
"\"\"\" Returns a list of stop words. Currently uses a list of words",
"list of token-posTag tuples return expanded list of tokens that includes synonyms and",
"add all synonyms and hypernyms for each token in input list of token-posTag",
"list of words in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords):",
"list of stop words. Currently uses a list of words in a text",
"lemmas of the synonyms bowTokens = set([t[0] for t in pos_tokens]) for synonym",
"bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns a list of stop words. Currently",
"any(c.isalpha() for c in t[0])] # query expansion expandedTokens = expand_text(pos_tokens) # add",
"text text = idea['content'].encode('utf-8', 'ignore') # split into sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text)",
"put in nextStack for s in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) #",
"* mag2) else: return 0.0 def get_wordnet_pos(treebank_tag): \"\"\" helper method to convert treebank",
"numpy as np from file_manager import read_data def cosine(doc1, doc2, doc_topic_weights): weights1 =",
"with synonyms synonyms = set() for item in pos_tokens: synsets = wn.synsets(item[0], get_wordnet_pos(item[1]))",
"Author: <NAME> <EMAIL> import nltk from nltk.corpus import wordnet as wn import numpy",
"nextStack.add(hypernym) # add lemmas from the current level of hypernyms to the master",
"def expand_text(pos_tokens): \"\"\" interface with wordnet to recursively add all synonyms and hypernyms",
"sentences (PunktSentenceTokenizer) sentences = nltk.sent_tokenize(text) # tokenize and pos tag words (TreeBank) pos_tokens",
"recursively add hypernyms nextStack = set(synonyms) # initialize stack while(len(nextStack)): currentStack = set(nextStack)",
"t[0] not in stopwords] # remove \"words\" with no letters in them! pos_tokens",
"for synonym in synonyms: for lemma in synonym.lemmas(): bowTokens.add(lemma.name()) # now recursively add",
"in a text file \"\"\" return read_data(\"englishstopwords-jc.txt\") def bag_of_words(ideas, stopwords): \"\"\" Initial processing",
"\"\"\" expandedText = [] data = [] for idea in ideas: # read",
"for t in pos_tokens if any(c.isalpha() for c in t[0])] # query expansion",
"weights2])) if mag1 and mag2: return dotProduct / (mag1 * mag2) else: return",
"\"\"\" Initial processing of ideas for Mike Terri's Ideaforest algorithm \"\"\" expandedText =",
"# query expansion expandedTokens = expand_text(pos_tokens) # add the enriched bag of words",
"list of tokens to be output # initialize with lemmas of the synonyms",
"in pos_tokens if t[0] not in stopwords] # remove \"words\" with no letters",
"#!/usr/bin/env python # Author: <NAME> <EMAIL> import nltk from nltk.corpus import wordnet as",
"# tokenize pos_tokens += nltk.pos_tag(tokens) # pos tag # remove stopwords pos_tokens =",
"in currentStack: for hypernym in s.hypernyms(): nextStack.add(hypernym) # add lemmas from the current",
"from nltk.corpus import wordnet as wn import numpy as np from file_manager import",
"of tokens for hypernym in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens))",
"in nextStack: for lemma in hypernym.lemmas(): bowTokens.add(lemma.name()) return sorted(list(bowTokens)) def get_stopwords(): \"\"\" Returns",
"tokens to be output # initialize with lemmas of the synonyms bowTokens ="
] |
[] |
[
"this is print demo again.\", file=f) f.close() if __name__ == \"__main__\": # end_demo()",
"in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365",
"python3 # -*- coding:utf-8 -*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import time",
"\"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) *",
"# author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _",
"is print demo again.\", file=f) f.close() if __name__ == \"__main__\": # end_demo() #",
"-*- coding:utf-8 -*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo():",
"\"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f) print(\"hello, this",
"\"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this",
"demo.\", file=f) print(\"hello, this is print demo again.\", file=f) f.close() if __name__ ==",
"print(\"hello, this is print demo again.\", file=f) f.close() if __name__ == \"__main__\": #",
"-*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for",
"range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01) print()",
"def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def",
"print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i",
"time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo():",
"\"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\",",
"end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in",
"end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \")",
"= 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 /",
"* 100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\",",
"+ 1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\"",
"bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100):",
"i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\", flush=True)",
"= open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f) print(\"hello, this is print",
"coding:utf-8 -*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\"",
"100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\",",
"\"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello,",
"for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days",
"f = open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f) print(\"hello, this is",
"\") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\",",
"def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i +",
"print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def",
"1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\",",
"print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\",",
"time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print()",
"sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f =",
"demo again.\", file=f) f.close() if __name__ == \"__main__\": # end_demo() # progress_demo() sep_demo()",
"def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f",
"sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f) print(\"hello,",
"\"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\"",
"365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)),",
"\"w\") print(\"hello, this is print demo.\", file=f) print(\"hello, this is print demo again.\",",
"file=f) print(\"hello, this is print demo again.\", file=f) f.close() if __name__ == \"__main__\":",
"print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\"",
"\"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\",",
"again.\", file=f) f.close() if __name__ == \"__main__\": # end_demo() # progress_demo() sep_demo() sysout_demo()",
"import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01)",
"\"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo():",
"/ days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\"",
"author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in",
"\"\"\" import time def end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True)",
"is print demo.\", file=f) print(\"hello, this is print demo again.\", file=f) f.close() if",
"# -*- coding:utf-8 -*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import time def",
"print demo.\", file=f) print(\"hello, this is print demo again.\", file=f) f.close() if __name__",
"sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is",
"time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days): print(\"\\r\",",
"days = 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100",
"for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\",",
"end_demo(): \"\"\"print结尾控制,加flush强制刷新\"\"\" for _ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo():",
"this is print demo.\", file=f) print(\"hello, this is print demo again.\", file=f) f.close()",
"#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu \"\"\" print函数展示 \"\"\" import",
"_ in range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days =",
"in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1) * 100 / days)), end=\"\", flush=True) time.sleep(0.01)",
"range(100): print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for",
"print(\"#\", end=\"\", flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i",
"flush=True) time.sleep(0.01) print() def progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days):",
"days)), end=\"\", flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" |",
"| \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is print",
"def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f)",
"open(\"print_demo.log\", \"w\") print(\"hello, this is print demo.\", file=f) print(\"hello, this is print demo",
"print demo again.\", file=f) f.close() if __name__ == \"__main__\": # end_demo() # progress_demo()",
"print(\"hello, this is print demo.\", file=f) print(\"hello, this is print demo again.\", file=f)",
"progress_demo(): \"\"\"使用\\r展示进度\"\"\" days = 365 for i in range(days): print(\"\\r\", \"progress:{}%\".format(round((i + 1)",
"print(\"name\", \"age\", \"score\", sep=\" | \") def sysout_demo(): \"\"\"将print的默认输出改到指定文件,而不是默认的屏幕\"\"\" f = open(\"print_demo.log\", \"w\")",
"flush=True) time.sleep(0.01) print() def sep_demo(): \"\"\"使用sep参数将结果使用指定分隔符分割\"\"\" print(\"name\", \"age\", \"score\", sep=\" | \") def"
] |
[
"FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView):",
") class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView):",
"SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model =",
"model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator",
"class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model",
"SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model =",
"class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model",
"FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model =",
"django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models import (",
"FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView):",
"class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model",
"SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model =",
"SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView):",
"model = FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator",
"= SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class",
"model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey",
"FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model =",
"class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model",
"import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class",
"-*- coding: utf-8 -*- from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView",
"class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model",
"class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model",
"ListView ) from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView):",
"UpdateView, ListView ) from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class",
"model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory",
"coding: utf-8 -*- from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView )",
"SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model =",
"class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model",
"SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model =",
"class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model",
"model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey",
"CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models import ( SFTPUser, SFTPUserKey, FileHistory,",
"= SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class",
"model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model = FileHistory",
"model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory",
"model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey",
"= SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class",
"class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model",
"class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model",
"SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView):",
"= SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class",
"model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator",
"model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey",
"SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model =",
"class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model",
"from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models import",
"( CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models import ( SFTPUser, SFTPUserKey,",
"<gh_stars>0 # -*- coding: utf-8 -*- from django.views.generic import ( CreateView, DeleteView, DetailView,",
"= SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class",
"FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class",
"SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView):",
"FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView):",
"from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model =",
"SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView):",
"FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model =",
"FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator class FileValidatorListView(ListView): model =",
"model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator class FileValidatorListView(ListView): model = FileValidator",
"SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model =",
"= FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator class",
"-*- from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models",
"= FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class",
"FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView):",
"SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView):",
"SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model =",
"= SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class",
"SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model",
"SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView):",
"= FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model = FileHistory class",
"class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model",
"( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView):",
"model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory",
"= FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class",
"FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView):",
"FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model =",
"= SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class",
"= FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class",
"SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView):",
"SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model =",
"= SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory class",
"model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser",
"# -*- coding: utf-8 -*- from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView,",
"class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class SFTPUserKeyListView(ListView): model = SFTPUserKey class FileHistoryCreateView(CreateView): model",
"FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser",
"model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey",
"model = SFTPUserKey class FileHistoryCreateView(CreateView): model = FileHistory class FileHistoryDeleteView(DeleteView): model = FileHistory",
"DeleteView, DetailView, UpdateView, ListView ) from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator,",
"SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView):",
"class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model",
"= SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser class",
"= FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class",
"SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView):",
"class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator class FileValidatorListView(ListView): model",
"model = SFTPUser class SFTPUserDeleteView(DeleteView): model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser",
"FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView): model = FileValidator class FileValidatorDetailView(DetailView): model =",
"DetailView, UpdateView, ListView ) from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, )",
"SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView):",
"model = FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator",
"SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser class SFTPUserDeleteView(DeleteView): model =",
".models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model = SFTPUser",
"FileHistoryDeleteView(DeleteView): model = FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model =",
"FileValidator class FileValidatorDetailView(DetailView): model = FileValidator class FileValidatorUpdateView(UpdateView): model = FileValidator class FileValidatorListView(ListView):",
"model = SFTPUser class SFTPUserDetailView(DetailView): model = SFTPUser class SFTPUserUpdateView(UpdateView): model = SFTPUser",
"FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model = FileValidator class FileValidatorDeleteView(DeleteView):",
"class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model = SFTPUserKey class SFTPUserKeyDeleteView(DeleteView): model",
"utf-8 -*- from django.views.generic import ( CreateView, DeleteView, DetailView, UpdateView, ListView ) from",
"import ( CreateView, DeleteView, DetailView, UpdateView, ListView ) from .models import ( SFTPUser,",
"class SFTPUserKeyDeleteView(DeleteView): model = SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model",
") from .models import ( SFTPUser, SFTPUserKey, FileHistory, FileValidator, ) class SFTPUserCreateView(CreateView): model",
"= FileHistory class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class",
"SFTPUserUpdateView(UpdateView): model = SFTPUser class SFTPUserListView(ListView): model = SFTPUser class SFTPUserKeyCreateView(CreateView): model =",
"FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model = FileHistory class FileValidatorCreateView(CreateView): model =",
"= SFTPUserKey class SFTPUserKeyDetailView(DetailView): model = SFTPUserKey class SFTPUserKeyUpdateView(UpdateView): model = SFTPUserKey class",
"class FileHistoryDetailView(DetailView): model = FileHistory class FileHistoryUpdateView(UpdateView): model = FileHistory class FileHistoryListView(ListView): model"
] |
[
"= ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data,",
"q, c = divmod(c, d3) if c: d[t] = c rd += q",
"return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data",
"if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is",
"order, cache=cache) * coeff key1 = (expr, symbol, 1) cache[key] = result return",
"lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1),",
"return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data == rdata: return",
"cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list",
"{} flag = False add = self.add for t, c in data.iteritems(): t1",
"else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace)",
"return number_div(cls, 1, coeff) * (lhs / term) if rhead is POW: base,",
"term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) +",
"Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3",
"rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs,",
"if inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if",
"rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data",
"pow_number = pow def neg(self, cls, expr): d = expr.data.copy() for key in",
"== rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL",
"data) def reevaluate(self, cls, data): r = cls(NUMBER, 0) for term, coeff in",
"+= term * coeff return r def to_ADD(self, Algebra, data, expr): return add_new(Algebra,",
"@init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def",
"rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data:",
"isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func, cls,",
"cls, c, c) if t1 is not t or c1 is not c:",
"cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2))",
"= multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in mdata.iteritems(): new_coeff = c",
"args) * coeff return result def integrate_indefinite(self, cls, data, expr, x): result =",
"return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if",
"mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in mdata.iteritems(): new_coeff =",
"intexp) d = {} for e,c in mdata.iteritems(): new_coeff = c df =",
"data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self,",
"rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return",
"is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1})",
"return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in",
"result += term.head.apply(cls, term.data, term, args) * coeff return result def integrate_indefinite(self, cls,",
"return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata",
"coeff) in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if",
"Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if",
"d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target): d",
"term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls,",
"coeff in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff",
"t**exp, c**exp if t==1: return cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF,",
"rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead,",
"rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff",
"d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self,",
"return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls,",
"term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW, (expr, intexp))",
"coeff) elif h2 is SUB or h2 is NEG or h2 is POS:",
"return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff = rdata return (lhs",
"return Algebra(NUMBER, 0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return",
"key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr):",
"lhs.data.copy() h2, d2 = rhs.pair if h2 is NUMBER: if d2 != 0:",
"self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs)",
"inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata)",
"return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc)",
"cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0)",
"APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW,",
"result def integrate_definite(self, cls, data, expr, x, a, b): result = cls(NUMBER, 0)",
"target) def diff(self, cls, data, expr, symbol, order, cache={}): key = (expr, symbol,",
"Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace):",
"term * coeff return r def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra,",
"self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if",
"MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata =",
"0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs,",
"1) elif h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term, coeff)",
"not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is",
"= NUMBER.walk(func, cls, c, c) if t1 is not t or c1 is",
"t, c) else: self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls, data, rhs,",
"in data.iteritems(): result += term.head.apply(cls, term.data, term, args) * coeff return result def",
"msg) #pragma: no cover else: return 'data must be dict instance but got",
"dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls,",
"None: d = {} result = cls(NUMBER, 0) for term, coeff in data.iteritems():",
"is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if",
"in lhs.data.items(): c /= d2 q, c = divmod(c, d3) if c: d[t]",
"expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls,",
"Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self,",
"0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d",
"r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data):",
"if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if",
"NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target) def diff(self, cls, data, expr,",
"data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self,",
"TERM_COEFF: term, coeff = rdata return number_div(cls, 1, coeff) * (lhs / term)",
"= base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func,",
"if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self,",
"SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF:",
"rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return",
"term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs,",
"return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or rhead",
"func(cls, self, data, target) def scan(self, proc, cls, data, target): for t, c",
"data, term, coeff) elif h2 is SUB or h2 is NEG or h2",
"rhead, rdata = rhs.pair if rhead is NUMBER: if not rdata: return lhs",
"else: return 'data must be dict instance but got %s' % (type(data)) #pragma:",
"expand(self, cls, expr): d = {} for t, c in expr.data.items(): self.add(cls, d,",
"= (expr, symbol, 1) cache[key] = result return result def apply(self, cls, data,",
"add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None):",
"rhead is ADD or rhead is EXP_COEFF_DICT or rhead is MUL or rhead",
"= [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls,",
"= dict_get_item(d) t,c = t**exp, c**exp if t==1: return cls(NUMBER, c) if c==1:",
"= expr.data.copy() for key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return",
"data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if",
"= t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data,",
"heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def",
"rhead, rdata = rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if",
"r = cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term,",
"for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is",
"POW: base, exp = rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT,",
"d2 q, c = divmod(c, d3) if c: d[t] = c rd +=",
"for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return",
"t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c) else: c1",
"flag = True add(cls, d, t1 * c1, inplace=True) if flag: r =",
"not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra,",
"flag = False add = self.add for t, c in data.iteritems(): t1 =",
"coeff = rdata return (lhs * term) * coeff if rhead is POW:",
"def expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW, (expr, intexp)) if intexp==0:",
"lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d =",
"d2 dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif",
"is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF: term, coeff =",
"base:exp}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1})",
"b) * coeff return result def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self,",
"cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls,",
"= lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term,",
"data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' %",
"exp==0: return cls(NUMBER, 1) if exp==1: return base d = base.data if len(d)==1:",
"else: dict_add_item(cls, data, rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls, data) def",
"cls, lhs, rhs, inplace=False): if inplace: data = lhs else: data = lhs.data.copy()",
"rcoeff = rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return",
"1), rdata elif rhead is SYMBOL: rterm, rcoeff = rhs, 1 elif rhead",
"lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0) data",
"is NUMBER: if not rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata",
"expr.data.copy() for key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG,",
"if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs,",
"exp): if exp==0: return cls(NUMBER, 1) if exp==1: return base d = base.data",
"return result def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra, expr): if",
"lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is",
"cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1} for base, exp",
"is BASE_EXP_DICT: data = {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base,",
"term, coeff in data.iteritems(): result += term.head.apply(cls, term.data, term, args) * coeff return",
"if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs)",
"= cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems(): r += term *",
"lhs.is_writable: data = lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return",
"BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data, t * c, inplace=True) else:",
"= term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return func(cls, self, data, target)",
"d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs,",
"cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER,",
"return cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF, (t, c)) return POW.new(cls,",
"term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if",
"* coeff return r def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff)",
"cls(NUMBER, 0) for term, coeff in data.iteritems(): r += term * coeff return",
"= c df = {} for e_i, ((base, exp), coeff) in zip(e, term_coeff_list):",
"term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff return result def algebra_pos(self, Algebra,",
"elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d",
"rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1) return",
"return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead",
"return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self,",
"if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls,",
"d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data, t",
"apply(self, cls, data, func, args): result = cls(NUMBER, 0) for term, coeff in",
"def integrate_definite(self, cls, data, expr, x, a, b): result = cls(NUMBER, 0) for",
"t1 is not t or c1 is not c: flag = True add(cls,",
"rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if rhead is NUMBER: if not",
"base, exp) if coeff is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df,",
"Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs: return lhs",
"t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c,",
"cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x,",
"-d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d = {} for t,",
"SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT:",
"isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self,",
"if len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp if t==1: return cls(NUMBER,",
"rdata = rhs.pair if rhead is NUMBER: if rdata==0: return rhs data =",
"dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2",
"rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False): if inplace:",
"h2, d2 = rhs.pair if h2 is NUMBER: if d2 != 0: dict_add_item(cls,",
"inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair",
"cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2",
"new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self,",
"Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self,",
"dict_get_item(d) t,c = t**exp, c**exp if t==1: return cls(NUMBER, c) if c==1: return",
"= rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is",
"msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' % (item,",
"r += term * coeff return r def term_coeff(self, cls, expr): term_coeff_dict =",
"self.add for t, c in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if",
"elif h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term, coeff) elif",
"term, coeff in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order, cache=cache) *",
"return 'data must be dict instance but got %s' % (type(data)) #pragma: no",
"if rhead is NUMBER: if not rdata: return lhs rterm, rcoeff = Algebra(NUMBER,",
"cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.apply(cls, term.data, term, args)",
"def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r",
"NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if rhead is",
"if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs,",
"{} rd = 0 for t,c in lhs.data.items(): c /= d2 q, c",
"is TERM_COEFF: term, coeff = rdata return number_div(cls, 1, coeff) * (lhs /",
"[(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d =",
"new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target): d =",
"inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra,",
"rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT,",
"* coeff return result def integrate_definite(self, cls, data, expr, x, a, b): result",
"base_exp_dict_add_item(cls, df, base, exp) if coeff is not 1: new_coeff *= coeff else:",
"term, coeff = rdata return (lhs * term) * coeff if rhead is",
"n = len(data) #if n<=1: # return 'data dictonary should have more than",
"return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra,",
"def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()])",
"data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1,",
"x, a, b) * coeff return result def algebra_pos(self, Algebra, expr): return expr",
"rterm, rcoeff = rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff = rdata",
"or rhead is MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs)",
"expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return",
"if flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return func(cls,",
"return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data)",
"r.data, r) return func(cls, self, data, target) def scan(self, proc, cls, data, target):",
"rdata return number_div(cls, 1, coeff) * (lhs / term) if rhead is POW:",
"module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is dict:",
"multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is",
"def scan(self, proc, cls, data, target): for t, c in data.iteritems(): t.head.scan(proc, cls,",
"expr, variables=None): if variables is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r",
"d = {} for e,c in mdata.iteritems(): new_coeff = c df = {}",
"data, target): d = {} flag = False add = self.add for t,",
"Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs if inplace:",
"= lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self,",
"r += term * coeff return r def to_ADD(self, Algebra, data, expr): return",
"rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT:",
"-rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls,",
"term, coeff = d2 dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls,",
"= rdata if lhs==base: return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1,",
"= result return result def apply(self, cls, data, func, args): result = cls(NUMBER,",
"d = {} rd = 0 for t,c in lhs.data.items(): c /= d2",
"import heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations()",
"term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return",
"= rhs / d2 d = {} rd = 0 for t,c in",
"term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return",
"df, base, exp) if coeff is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls,",
"df = {} for e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if e_i:",
"d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra,",
"d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs:",
"return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r = cls(NUMBER, 0) for term,",
"sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls,",
"data, expr, symbol, order, cache={}): key = (expr, symbol, order) result = cache.get(key)",
"= self.add for t, c in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t)",
"** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d)",
"lhs, rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if",
"if result is None: d = {} result = cls(NUMBER, 0) for term,",
"rhead is NUMBER: if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata)",
"= rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD:",
"Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if",
"args): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.apply(cls,",
"= {} flag = False add = self.add for t, c in data.iteritems():",
"or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term,",
"number_div(cls, 1, coeff) * (lhs / term) if rhead is POW: base, exp",
"def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d",
"if lhs==base: return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if",
"self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls,",
"NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def",
"TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma:",
"term_coeff_list = [(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp)",
"coeff) for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {}",
"assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd",
"d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d =",
"None: return result if result is None: d = {} result = cls(NUMBER,",
"term.data, term, x) * coeff return result def integrate_definite(self, cls, data, expr, x,",
"term, x, a, b) * coeff return result def algebra_pos(self, Algebra, expr): return",
"term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else:",
"is_data_ok(self, cls, data): if type(data) is dict: n = len(data) #if n<=1: #",
"d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata",
"exp), coeff) in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp)",
"term, coeff in data.iteritems(): r += term * coeff return r def term_coeff(self,",
"init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class",
"Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead,",
"data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base, exp): if exp==0:",
"return t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number = pow",
"ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base, exp): if exp==0: return cls(NUMBER,",
"c /= d2 q, c = divmod(c, d3) if c: d[t] = c",
"term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r = cls(NUMBER, 0) for term, coeff",
"op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is SUB or h2 is NEG",
"if c: d[t] = c rd += q s = term_coeff_dict_new(Algebra, d) if",
"= commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs))",
"proc(cls, self, data, target) def diff(self, cls, data, expr, symbol, order, cache={}): key",
"+= term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff return result def algebra_pos(self,",
"rhs): if lhs.is_writable: data = lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs,",
"dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1)",
"POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL",
"for term, coeff in data.iteritems(): r += term * coeff return r def",
"for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return",
"lhs, rhs, inplace=False): if inplace: data = lhs else: data = lhs.data.copy() h2,",
"in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff return",
"return (lhs * term) * coeff if rhead is POW: base, exp =",
"Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs,",
"data = lhs else: data = lhs.data.copy() h2, d2 = rhs.pair if h2",
"rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead",
"inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return",
"algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata =",
"h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD: for op in",
"but got %s' % (type(data)) #pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT'",
"BASE_EXP_DICT: data = {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp)",
"term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff = rdata return (lhs *",
"inplace): if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs)",
"return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return",
"lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self),",
"<filename>sympycore/heads/term_coeff_dict.py<gh_stars>10-100 __all__ = ['TERM_COEFF_DICT'] from .base import heads, heads_precedence, ArithmeticHead, Pair from ..core",
"for t, c in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if isinstance(c,",
"return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or rhead is APPLY: return",
"data=%s: %s' % (item, msg) #pragma: no cover else: return 'data must be",
"= gcd(d1, rhs) d3 = rhs / d2 d = {} rd =",
"= {} for e,c in mdata.iteritems(): new_coeff = c df = {} for",
"= lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls,",
"def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata",
"data.iteritems(): r += term * coeff return r def to_ADD(self, Algebra, data, expr):",
"return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if",
"def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self,",
"dict: n = len(data) #if n<=1: # return 'data dictonary should have more",
"expr, 1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data = lhs.data else:",
"else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs, 1) if inplace: return",
"* c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs, 1)",
"rdata elif rhead is SYMBOL: rterm, rcoeff = rhs, 1 elif rhead is",
"if rhead is POW: base, exp = rdata if lhs==base: return pow_new(cls, (lhs,",
"ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module):",
"= False add = self.add for t, c in data.iteritems(): t1 = t.head.walk(func,",
"cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r)",
"cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs,",
"lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d)",
"term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs):",
"c: flag = True add(cls, d, t1 * c1, inplace=True) if flag: r",
"True add(cls, d, t1 * c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d)",
"target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c, target)",
"cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d = {} for t, c in",
"expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list),",
"or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair",
"TERM_COEFF: term, coeff = rdata return (lhs * term) * coeff if rhead",
"d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER,",
"Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if",
"coeff return result def integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER, 0)",
"return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else:",
"= -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs,",
"d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra,",
"return result if result is None: d = {} result = cls(NUMBER, 0)",
"is ADD or rhead is EXP_COEFF_DICT or rhead is MUL or rhead is",
"rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead",
"data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls,",
"def pow(self, cls, base, exp): if exp==0: return cls(NUMBER, 1) if exp==1: return",
"return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d = {} for t, c",
"is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if",
"rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0) data =",
"if intexp==0: return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff)",
"cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data,",
"return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d",
"expr): d = expr.data.copy() for key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT,",
"rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead is SYMBOL:",
"d2) elif h2 is ADD: for op in d2: term, coeff = op.term_coeff()",
"(lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1}",
"if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d: d[key] = -d[key] return",
"*= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not 1: new_coeff",
"d2 = gcd(d1, rhs) d3 = rhs / d2 d = {} rd",
"rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs,",
"else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems(): r +=",
"1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return",
"rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead,",
"result return result def apply(self, cls, data, func, args): result = cls(NUMBER, 0)",
"data, rhs, 1) elif h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data,",
"inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return",
"is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD: for op in d2:",
"for t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc,",
"expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d: d[key] = -d[key]",
"s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs,",
"lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def",
"t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number = pow def",
"d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead,",
"rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT:",
"instance but got %s' % (type(data)) #pragma: no cover return def __repr__(self): return",
"neg(self, cls, expr): d = expr.data.copy() for key in d: d[key] = -d[key]",
"mdata.iteritems(): new_coeff = c df = {} for e_i, ((base, exp), coeff) in",
"= base_exp_dict_get_coefficient(cls, d2) if c is not None: d = d2.copy() del d[c]",
"rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 =",
"lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT:",
"= lhs.data if rhead is ADD or rhead is EXP_COEFF_DICT or rhead is",
"super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'):",
"return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False): if inplace: data =",
"key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def",
"c df = {} for e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if",
"c) if t1 is not t or c1 is not c: flag =",
"Algebra, lhs, rhs, inplace): if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data,",
"h2 is NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is",
"= rhs.pair if h2 is NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER,",
"c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target) def diff(self,",
"def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy()",
"is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is",
"rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs",
"d2) if c is not None: d = d2.copy() del d[c] t =",
"return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER,",
"intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list = [(term.base_exp(),",
"op in d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2",
"rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self),",
"= gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs / d2 d =",
"if coeff is not 1: new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls,",
"TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is dict: n = len(data) #if",
"d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs / d2 d",
"r def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in",
"-1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead",
"inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata,",
"if c is not None: d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls,",
"data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else:",
"expr.data.copy() for key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self,",
"h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is not None: d",
"= lhs.data.copy() h2, d2 = rhs.pair if h2 is NUMBER: if d2 !=",
"TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT:",
"t1 * c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head,",
"if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 =",
"lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d,",
"to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is None: r = cls(EXP_COEFF_DICT, Pair((),",
"raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c",
"if coeff is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i)",
"algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER:",
"lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs,",
"data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False): if",
"cls, data, expr, variables=None): if variables is None: r = cls(EXP_COEFF_DICT, Pair((), {}))",
"cache[key] = result return result def apply(self, cls, data, func, args): result =",
"return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs,",
"zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is",
"a, b) * coeff return result def algebra_pos(self, Algebra, expr): return expr def",
"= lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)])",
"rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead",
"target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target) def diff(self, cls,",
"return result def apply(self, cls, data, func, args): result = cls(NUMBER, 0) for",
"rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace)",
"is not None: d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if",
"coeff in data.iteritems(): r += term * coeff return r def term_coeff(self, cls,",
"term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def",
"= lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls,",
"c**exp if t==1: return cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF, (t,",
"rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra,",
"NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data == rdata:",
"rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is not",
"dict_add_item(cls, data, rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self,",
"cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def",
"c) else: c1 = NUMBER.walk(func, cls, c, c) if t1 is not t",
"else: data = lhs.data.copy() h2, d2 = rhs.pair if h2 is NUMBER: if",
"exp==1: return base d = base.data if len(d)==1: t,c = dict_get_item(d) t,c =",
"ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff)",
"if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is",
"if t1 is not t or c1 is not c: flag = True",
"rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if rhs==1: return",
"data) def add_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy()",
"data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is None: r =",
"= rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra,",
"base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def",
"elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is not None:",
"data, cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif",
"cache=cache) * coeff key1 = (expr, symbol, 1) cache[key] = result return result",
"d) def walk(self, func, cls, data, target): d = {} flag = False",
"TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead",
"cls, c, target) proc(cls, self, data, target) def diff(self, cls, data, expr, symbol,",
"t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c)",
"elif h2 is ADD: for op in d2: term, coeff = op.term_coeff() dict_add_item(cls,",
"rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or",
"d2 = rhs.pair if h2 is NUMBER: if d2 != 0: dict_add_item(cls, data,",
"def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self,",
"cls, data, target): d = {} flag = False add = self.add for",
"2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls,",
"0 for t,c in lhs.data.items(): c /= d2 q, c = divmod(c, d3)",
"rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs,",
"lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs):",
"data, target): for t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c,",
"d = {} result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result",
"or c1 is not c: flag = True add(cls, d, t1 * c1,",
"ADD or rhead is EXP_COEFF_DICT or rhead is MUL or rhead is NEG:",
"= {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls,",
"rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV,",
"return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs: return",
"h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term, coeff) elif h2",
"/ d2 d = {} rd = 0 for t,c in lhs.data.items(): c",
"rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD",
"else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target) def diff(self, cls, data,",
"if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return",
"*= coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return",
"cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x)",
"(lhs * term) * coeff if rhead is POW: base, exp = rdata",
"d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT:",
"{lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return",
"Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return",
"= cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term,",
"not None: return result if result is None: d = {} result =",
"TERM_COEFF: rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata,",
"return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if",
"or rhead is EXP_COEFF_DICT or rhead is MUL or rhead is NEG: rhs",
"TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra,",
"= op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is SUB or h2 is",
"rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return",
"1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data = lhs.data else: data",
"d, t1 * c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d) return func(cls,",
"= (expr, symbol, order) result = cache.get(key) if result is not None: return",
"term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata =",
"from .base import heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads()",
"intexp): if intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1) if",
"rhs): if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return",
"if intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1:",
"Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients =",
"cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r = cls(NUMBER,",
"c in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1",
"return expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata =",
"for term, coeff in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order, cache=cache)",
"is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return",
"= rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if",
"-exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base,",
"return func(cls, r.head, r.data, r) return func(cls, self, data, target) def scan(self, proc,",
"data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls,",
"return term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target): d = {} flag",
"= rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self),",
"h2 is SUB or h2 is NEG or h2 is POS: raise NotImplementedError(`self,",
"{} for e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if e_i: if e_i==1:",
"if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d =",
"is not None: return result if result is None: d = {} result",
"t1 = t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func, cls,",
"h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF: term, coeff",
"{lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data)",
"term, coeff = rdata return number_div(cls, 1, coeff) * (lhs / term) if",
"rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d)",
"rhs:-1}) if rhead is TERM_COEFF: term, coeff = rdata return number_div(cls, 1, coeff)",
"is MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata",
"* coeff if rhead is POW: base, exp = rdata if lhs==base: return",
"{} for t, c in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return",
"result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data,",
"rhs) rhead, rdata = rhs.pair if rhead is NUMBER: if not rdata: return",
"intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata",
"for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a, b)",
"(base, exp)) pow_number = pow def neg(self, cls, expr): d = expr.data.copy() for",
"to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def",
"or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if",
"0) for term, coeff in data.iteritems(): r += term * coeff return r",
"d2 d = {} rd = 0 for t,c in lhs.data.items(): c /=",
"= True add(cls, d, t1 * c1, inplace=True) if flag: r = term_coeff_dict_new(cls,",
"dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT,",
"coeff if rhead is POW: base, exp = rdata if lhs==base: return POW.new(cls,",
"rhead is SYMBOL: rterm, rcoeff = rhs, 1 elif rhead is TERM_COEFF: rterm,",
"is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs, rhs, inplace)",
"return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base, exp): if exp==0: return",
"(type(data)) #pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict):",
"lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff",
"= term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV,",
"rdata = rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return",
"lhs, rhs): if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs)",
"if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra,",
"target) def scan(self, proc, cls, data, target): for t, c in data.iteritems(): t.head.scan(proc,",
"rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra,",
"rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if",
"is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {}))",
"data, expr, x, a, b): result = cls(NUMBER, 0) for term, coeff in",
"rhs / d2 d = {} rd = 0 for t,c in lhs.data.items():",
"lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls,",
"from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data):",
"term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace)",
"else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff)",
"term) if rhead is POW: base, exp = rdata if lhs==base: return pow_new(cls,",
"1) if inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs):",
"data) def add(self, cls, lhs, rhs, inplace=False): if inplace: data = lhs else:",
"lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs,",
"self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr,",
"1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs)",
"r = cls(NUMBER, 0) for term, coeff in data.iteritems(): r += term *",
"r.head, r.data, r) return func(cls, self, data, target) def scan(self, proc, cls, data,",
"rdata) if rhead is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1) return",
"import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients",
"cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d =",
"d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra,",
"return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base, exp):",
"r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems(): r += term",
"s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)])",
"return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if rhs==0: return",
"POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if",
"result if result is None: d = {} result = cls(NUMBER, 0) for",
"r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return func(cls, self, data,",
"is NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2",
"data, expr, variables=None): if variables is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else:",
"symbol, order, cache={}): key = (expr, symbol, order) result = cache.get(key) if result",
"rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls,",
"return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data)",
"rhs, inplace): if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1),",
"coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in",
"return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d,",
"is NUMBER: if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return",
"return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs, rhs, inplace) TERM_COEFF_DICT =",
"1 elif rhead is TERM_COEFF: rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT:",
"is NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT:",
"len(data) #if n<=1: # return 'data dictonary should have more than 1 item'",
"lhs, rhs): if lhs.is_writable: data = lhs.data else: data = lhs.data.copy() self.add(cls, data,",
"rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data)",
"in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is None: r",
"for key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls,",
"df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls, data,",
"Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data,",
"= -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d = {} for",
"+ rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs,",
"coeff return result def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra, expr):",
"gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs / d2 d = {}",
"term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs,",
"inplace=False): if inplace: data = lhs else: data = lhs.data.copy() h2, d2 =",
"lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def",
"r) return func(cls, self, data, target) def scan(self, proc, cls, data, target): for",
"rdata = rhs.pair if rhead is NUMBER: if not rdata: return lhs rterm,",
"cover else: return 'data must be dict instance but got %s' % (type(data))",
"super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'):",
"more than 1 item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True)",
"term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if rhs==0: return lhs data =",
"return r def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff",
"lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if rhs==1:",
"d = base.data if len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp if",
"is EXP_COEFF_DICT or rhead is MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra,",
"term, coeff) elif h2 is SUB or h2 is NEG or h2 is",
"= multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is dict: n",
"if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data, t *",
"rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff = rdata elif rhead is",
"result is not None: return result if result is None: d = {}",
"data, t, c) else: self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls, data,",
"if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)])",
"= BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls,",
"/ term) if rhead is POW: base, exp = rdata if lhs==base: return",
"for t,c in lhs.data.items(): c /= d2 q, c = divmod(c, d3) if",
"= ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs,",
"be dict instance but got %s' % (type(data)) #pragma: no cover return def",
"from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory",
"def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return",
"return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm,",
"in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self,",
"c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target)",
"dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs, 1) if inplace: return lhs",
"data) if rhead is TERM_COEFF: term, coeff = rdata return (lhs * term)",
"d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is SUB",
"def expand(self, cls, expr): d = {} for t, c in expr.data.items(): self.add(cls,",
"NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c",
"del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t,",
"= rhs.pair if rhead is NUMBER: if not rdata: return lhs rterm, rcoeff",
"if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is not 1:",
"c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs, 1) if",
"not None: d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head",
"+ rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace):",
"def apply(self, cls, data, func, args): result = cls(NUMBER, 0) for term, coeff",
"% (item, msg) #pragma: no cover else: return 'data must be dict instance",
"term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if rhs==0: return lhs data =",
"ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls,",
"= rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self),",
"data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs,",
"rhead is TERM_COEFF: term, coeff = rdata return (lhs * term) * coeff",
"if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs if",
"c rd += q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs,",
"= Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm, rcoeff = rhs, 1",
"base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1} for base, exp in rdata.iteritems():",
"t * c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs,",
"data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self,",
"multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is dict: n =",
"lhs.data.items(): c /= d2 q, c = divmod(c, d3) if c: d[t] =",
"return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra,",
"t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data, t * c,",
"base_exp_dict_get_coefficient(cls, d2) if c is not None: d = d2.copy() del d[c] t",
"rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0:",
"= d2 dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2)",
"* coeff key1 = (expr, symbol, 1) cache[key] = result return result def",
"data, func, args): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result",
"def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER,",
"lhs, rhs) def pow(self, cls, base, exp): if exp==0: return cls(NUMBER, 1) if",
"coeff return r def term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return",
"d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'):",
"1: new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term,",
"= {} for e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if e_i: if",
"elif h2 is SUB or h2 is NEG or h2 is POS: raise",
"data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result def integrate_definite(self,",
"lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def",
"Algebra, expr): return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy()",
"term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result def integrate_definite(self, cls, data, expr,",
"= expr.data.copy() for key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def",
"coeff key1 = (expr, symbol, 1) cache[key] = result return result def apply(self,",
"d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm,",
"for e,c in mdata.iteritems(): new_coeff = c df = {} for e_i, ((base,",
"cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number = pow def neg(self, cls,",
"return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no cover else: return 'data",
"return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or rhead is APPLY: return",
"'data must be dict instance but got %s' % (type(data)) #pragma: no cover",
"def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data = lhs.data else: data =",
"(cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair",
"init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients",
"cls(NUMBER, 1) if exp==1: return base d = base.data if len(d)==1: t,c =",
"rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs,",
"= lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra,",
"= pow def neg(self, cls, expr): d = expr.data.copy() for key in d:",
"return 'data dictonary should have more than 1 item' for item in data.iteritems():",
"rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def",
"exp) if coeff is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base,",
"coeff return result def integrate_definite(self, cls, data, expr, x, a, b): result =",
"lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs,",
"1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or rhead is APPLY:",
"1) if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff in",
"d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs,",
"or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c =",
"cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol,",
"return result def integrate_definite(self, cls, data, expr, x, a, b): result = cls(NUMBER,",
"self, data, target) def diff(self, cls, data, expr, symbol, order, cache={}): key =",
"def is_data_ok(self, cls, data): if type(data) is dict: n = len(data) #if n<=1:",
"self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False):",
"base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls,",
"result += term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff return result def",
"multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in mdata.iteritems(): new_coeff = c df",
"algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d =",
"ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs)",
"{lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1)",
"exp)) pow_number = pow def neg(self, cls, expr): d = expr.data.copy() for key",
"Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data",
"dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data =",
"expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self,",
"return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d)",
"t or c1 is not c: flag = True add(cls, d, t1 *",
"term, coeff in data.iteritems(): r += term * coeff return r def to_ADD(self,",
"cls, t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c) else:",
"new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target): d = {}",
"(lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy()",
"ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER,",
"than 1 item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if",
"super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra,",
"symbol, order, cache=cache) * coeff key1 = (expr, symbol, 1) cache[key] = result",
"rhead is NUMBER: if not rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1),",
"cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT,",
"0) for term, coeff in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order,",
"d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs,",
"result += term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff key1 = (expr,",
"result def apply(self, cls, data, func, args): result = cls(NUMBER, 0) for term,",
".base import heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers()",
"lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not",
"__repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc",
"t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target) else: NUMBER.scan(proc,",
"c1 = NUMBER.walk(func, cls, c, c) if t1 is not t or c1",
"cls, expr): d = {} for t, c in expr.data.items(): self.add(cls, d, t.expand()",
"commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def",
"1, coeff) * (lhs / term) if rhead is POW: base, exp =",
"in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in mdata.iteritems():",
"in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs,",
"cls, data, expr, x): result = cls(NUMBER, 0) for term, coeff in data.iteritems():",
"return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair",
"data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff return result",
"if msg: return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no cover else:",
"if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is not 1: new_coeff *=",
"if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if",
"{lhs:1, rhs:-1}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1,",
"rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata =",
"c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data,",
"_init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls,",
"lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def",
"Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems():",
"data, expr, x): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result",
"Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1),",
"func, cls, data, target): d = {} flag = False add = self.add",
"rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs:",
"rhead is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1,",
"lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra,",
"for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF",
"term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1",
"expr): return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for",
"rhs.pair if h2 is NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1),",
"coeff = d2 dict_add_item(cls, data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data,",
"sub_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data,",
"e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df,",
"cls, c.data, c) else: c1 = NUMBER.walk(func, cls, c, c) if t1 is",
"rdata = rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead",
"= cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff",
"* term) * coeff if rhead is POW: base, exp = rdata if",
"cls, expr, intexp): if intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER,",
"return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data,",
"cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data =",
"is POW: base, exp = rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return",
"cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF,",
"expr, x): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result +=",
"[cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data,",
"term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self,",
"if type(data) is dict: n = len(data) #if n<=1: # return 'data dictonary",
"inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1,",
"def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1",
"return cls(NUMBER, 1) if exp==1: return base d = base.data if len(d)==1: t,c",
"if not rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead",
"rhead is TERM_COEFF: term, coeff = rdata return number_div(cls, 1, coeff) * (lhs",
"#pragma: no cover else: return 'data must be dict instance but got %s'",
"symbol, 1) cache[key] = result return result def apply(self, cls, data, func, args):",
"c.data, c) else: c1 = NUMBER.walk(func, cls, c, c) if t1 is not",
"inplace): rhead, rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is",
"rhs) d3 = rhs / d2 d = {} rd = 0 for",
"is dict: n = len(data) #if n<=1: # return 'data dictonary should have",
"got %s' % (type(data)) #pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT' def",
"return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data",
"t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls,",
"d3) if c: d[t] = c rd += q s = term_coeff_dict_new(Algebra, d)",
"in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr): c.head.scan(proc, cls, c.data, target)",
"cls, lhs, rhs): if lhs.is_writable: data = lhs.data else: data = lhs.data.copy() self.add(cls,",
"term.data, term, symbol, order, cache=cache) * coeff key1 = (expr, symbol, 1) cache[key]",
"term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False): if inplace: data = lhs",
"= lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs,",
"is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff =",
"in mdata.iteritems(): new_coeff = c df = {} for e_i, ((base, exp), coeff)",
"data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs):",
"self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead,",
"BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data,",
"'data dictonary should have more than 1 item' for item in data.iteritems(): msg",
"Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from",
"lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d",
"term, args) * coeff return result def integrate_indefinite(self, cls, data, expr, x): result",
"gcd(d1, rhs) d3 = rhs / d2 d = {} rd = 0",
"is None: d = {} result = cls(NUMBER, 0) for term, coeff in",
"rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace)",
"{lhs:1, base:exp}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1,",
"False add = self.add for t, c in data.iteritems(): t1 = t.head.walk(func, cls,",
"base, exp = rdata if lhs==base: return POW.new(cls, (lhs, exp + 1)) return",
"have more than 1 item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item,",
"if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d,",
"else: self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else:",
"if variables is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT,",
"item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return",
"def commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER:",
"t==1: return cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF, (t, c)) return",
"walk(self, func, cls, data, target): d = {} flag = False add =",
"if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func,",
"rhs, 1) elif h2 is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term,",
"cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems(): r += term * coeff",
"if lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead",
"inplace=True) return term_coeff_dict_new(cls, data) def add(self, cls, lhs, rhs, inplace=False): if inplace: data",
"is SYMBOL: rterm, rcoeff = rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff",
"TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self,",
"in data.iteritems(): r += term * coeff return r def term_coeff(self, cls, expr):",
"(lhs / term) if rhead is POW: base, exp = rdata if lhs==base:",
"rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm, rcoeff =",
"divmod(c, d3) if c: d[t] = c rd += q s = term_coeff_dict_new(Algebra,",
"def commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER:",
"target): d = {} flag = False add = self.add for t, c",
"rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls,",
"expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c in mdata.iteritems(): new_coeff",
"= c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func, cls, c, c) if",
"+= q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return",
"for key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr)",
"rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead",
"c, target) proc(cls, self, data, target) def diff(self, cls, data, expr, symbol, order,",
"func(cls, r.head, r.data, r) return func(cls, self, data, target) def scan(self, proc, cls,",
"lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values()) d2",
"= rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff = rdata elif rhead",
"cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number =",
"data, t * c, inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data,",
"return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if rhs==0: return lhs data",
"cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW,",
"rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data)",
"+= term.head.apply(cls, term.data, term, args) * coeff return result def integrate_indefinite(self, cls, data,",
"rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace:",
"d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c)",
"return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1: return expr",
"dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs,",
"self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if",
"cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base,",
"c) if c==1: return t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp))",
"rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if",
"lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra,",
"term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a, b) *",
"SUB or h2 is NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif",
"data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF:",
"d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER,",
"term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff return",
"expr): d = {} for t, c in expr.data.items(): self.add(cls, d, t.expand() *",
"item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no",
"((base, exp), coeff) in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base,",
"base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls,",
"data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1 = c.head.walk(func,",
"cls, data, func, args): result = cls(NUMBER, 0) for term, coeff in data.iteritems():",
"new_coeff = c df = {} for e_i, ((base, exp), coeff) in zip(e,",
"1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d = lhs.data.copy()",
"term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target): d = {} flag =",
"term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT,",
"def walk(self, func, cls, data, target): d = {} flag = False add",
"data = lhs.data.copy() h2, d2 = rhs.pair if h2 is NUMBER: if d2",
"base d = base.data if len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp",
"is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy()",
"{})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in data.iteritems(): r",
"coeff in data.iteritems(): result += term.head.apply(cls, term.data, term, args) * coeff return result",
"e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is not 1: new_coeff *= coeff",
"= cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.apply(cls, term.data, term,",
"exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or rhead",
"result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.diff(cls, term.data,",
"rhead is MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead,",
"rhead is POW: base, exp = rdata if lhs==base: return POW.new(cls, (lhs, exp",
"= {} for t, c in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True)",
"t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else:",
"t) if isinstance(c, Expr): c1 = c.head.walk(func, cls, c.data, c) else: c1 =",
"1) if exp==1: return base d = base.data if len(d)==1: t,c = dict_get_item(d)",
"ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs,",
"d = expr.data.copy() for key in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d)",
"rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if rhead is NUMBER:",
"if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if",
"data, term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is",
"if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs, rhs): if",
"tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True):",
"data.iteritems(): r += term * coeff return r def term_coeff(self, cls, expr): term_coeff_dict",
"= rdata return number_div(cls, 1, coeff) * (lhs / term) if rhead is",
"return lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs /",
"add_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data,",
"data) def sub_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy()",
"rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD or rhead is",
"is ADD: for op in d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term,",
"term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm,",
"{} for e,c in mdata.iteritems(): new_coeff = c df = {} for e_i,",
"if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1,",
"lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: if rdata==0: return",
"rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs, rhs, inplace):",
"if rhead is TERM_COEFF: term, coeff = rdata return (lhs * term) *",
"(lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair if",
"rhead is POW: base, exp = rdata if lhs==base: return pow_new(cls, (lhs, 1-exp))",
"is not 1: new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls,",
"-d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace):",
"inplace=True) if flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return",
"rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs)",
"Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD or rhead is EXP_COEFF_DICT or",
"result is None: d = {} result = cls(NUMBER, 0) for term, coeff",
"rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is",
"coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not 1: new_coeff *=",
"[lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair",
"lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if rhs==0: return lhs",
"rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra,",
"rhs, inplace=False): if inplace: data = lhs else: data = lhs.data.copy() h2, d2",
"1) else: dict_add_item(cls, data, rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls, data)",
"pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data =",
"self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra,",
"algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER:",
"inplace: data = lhs else: data = lhs.data.copy() h2, d2 = rhs.pair if",
"Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 = gcd(*lhs.data.values())",
"return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return",
"return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key",
"x): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls,",
"0) for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) *",
"return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair if",
"reevaluate(self, cls, data): r = cls(NUMBER, 0) for term, coeff in data.iteritems(): r",
"d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls, data,",
"return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self,",
"TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if",
"+ 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or rhead is",
"'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no cover else: return 'data must",
"* coeff return result def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra,",
"def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs: return lhs if inplace:",
"d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls,",
"data, d2) elif h2 is ADD: for op in d2: term, coeff =",
"% (type(data)) #pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls,",
"= rdata return (lhs * term) * coeff if rhead is POW: base,",
"is not t or c1 is not c: flag = True add(cls, d,",
"lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs):",
"len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp if t==1: return cls(NUMBER, c)",
"in data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff key1",
"coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls,",
"coeff is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if",
"data.iteritems(): result += term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff key1 =",
"algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d: d[key]",
"rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs,",
"return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW, (expr,",
"symbol, order) result = cache.get(key) if result is not None: return result if",
"variables is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables,",
"is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2)",
"add = self.add for t, c in data.iteritems(): t1 = t.head.walk(func, cls, t.data,",
"%s' % (item, msg) #pragma: no cover else: return 'data must be dict",
"expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in",
"* coeff return result def integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER,",
"base, exp): if exp==0: return cls(NUMBER, 1) if exp==1: return base d =",
"= cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term,",
"1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1} for",
"base, exp*e_i) if coeff is not 1: new_coeff *= coeff ** e_i new_term",
"exp*e_i) if coeff is not 1: new_coeff *= coeff ** e_i new_term =",
"coeff in data.iteritems(): r += term * coeff return r def to_ADD(self, Algebra,",
"cache.get(key) if result is not None: return result if result is None: d",
"d = {} flag = False add = self.add for t, c in",
"if not rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra,",
"= divmod(c, d3) if c: d[t] = c rd += q s =",
"def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is None: r = cls(EXP_COEFF_DICT,",
"= base.data if len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp if t==1:",
"h2 is NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif",
"intexp==0: return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for",
"return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata",
"data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs): d",
"algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0)",
"else: c1 = NUMBER.walk(func, cls, c, c) if t1 is not t or",
"term.data, term, args) * coeff return result def integrate_indefinite(self, cls, data, expr, x):",
"rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self,",
"if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy()",
"is POW: base, exp = rdata if lhs==base: return POW.new(cls, (lhs, exp +",
"a, b): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result +=",
"Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not",
"-rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata =",
"rdata, rhs) rhead, rdata = rhs.pair if rhead is NUMBER: if not rdata:",
"rhs, 1) else: dict_add_item(cls, data, rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls,",
"d = expr.data.copy() for key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d)",
"d) def expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW, (expr, intexp)) if",
"if rhead is ADD or rhead is EXP_COEFF_DICT or rhead is MUL or",
"return POW.new(cls, (base, exp)) pow_number = pow def neg(self, cls, expr): d =",
"..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import",
"= rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if rhead is NUMBER: if",
"lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1)",
"t, c in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if isinstance(c, Expr):",
"term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d)",
"['TERM_COEFF_DICT'] from .base import heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr",
"0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number",
"c1 is not c: flag = True add(cls, d, t1 * c1, inplace=True)",
"e,c in mdata.iteritems(): new_coeff = c df = {} for e_i, ((base, exp),",
"return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs,",
"+= term * coeff return r def term_coeff(self, cls, expr): term_coeff_dict = expr.data",
"order) result = cache.get(key) if result is not None: return result if result",
"h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls,",
"= 0 for t,c in lhs.data.items(): c /= d2 q, c = divmod(c,",
"BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is not None: d = d2.copy()",
"rdata = rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD or",
"= t**exp, c**exp if t==1: return cls(NUMBER, c) if c==1: return t return",
"= {} result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result +=",
"1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata",
"d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF:",
"rhs:-1}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1})",
"x) * coeff return result def integrate_definite(self, cls, data, expr, x, a, b):",
"in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result def",
"cls, data): r = cls(NUMBER, 0) for term, coeff in data.iteritems(): r +=",
"term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead",
"Expr): c1 = c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func, cls, c,",
"term, symbol, order, cache=cache) * coeff key1 = (expr, symbol, 1) cache[key] =",
"APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff = rdata",
"e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is not 1: new_coeff",
"..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if",
"c is not None: d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d)",
"return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data",
"%s' % (type(data)) #pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self,",
"elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF: term,",
"__all__ = ['TERM_COEFF_DICT'] from .base import heads, heads_precedence, ArithmeticHead, Pair from ..core import",
"rhead is EXP_COEFF_DICT or rhead is MUL or rhead is NEG: rhs =",
"BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls,",
"rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs, 2)) return cls(BASE_EXP_DICT, {lhs:1, rhs:1})",
"(expr, symbol, 1) cache[key] = result return result def apply(self, cls, data, func,",
"cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if rhs==0:",
"is TERM_COEFF: term, coeff = d2 dict_add_item(cls, data, term, coeff) elif h2 is",
"if lhs.is_writable: data = lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True)",
"item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s:",
"is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata, rhs) rhead, rdata = rhs.pair if rhead",
"rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d =",
"not t or c1 is not c: flag = True add(cls, d, t1",
"rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return",
"result def integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER, 0) for term,",
"t,c in lhs.data.items(): c /= d2 q, c = divmod(c, d3) if c:",
"ldata, rdata) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_dict(Algebra, d, rdata) return term_coeff_dict_new(Algebra,",
"x, a, b): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result",
"d) def expand(self, cls, expr): d = {} for t, c in expr.data.items():",
"rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead",
"rdata if lhs==base: return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp})",
"term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return func(cls, self, data, target) def",
"d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp):",
"#pragma: no cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r",
"= cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.diff(cls, term.data, term,",
"dict instance but got %s' % (type(data)) #pragma: no cover return def __repr__(self):",
"cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT,",
"1 item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg:",
"flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r) return func(cls, self,",
"integrate_definite(self, cls, data, expr, x, a, b): result = cls(NUMBER, 0) for term,",
"return result def integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER, 0) for",
"result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.apply(cls, term.data,",
"return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra,",
"return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls, lhs, rhs): rhead, rdata",
"must be dict instance but got %s' % (type(data)) #pragma: no cover return",
"rhead is TERM_COEFF: rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT: if inplace:",
"data, target) def scan(self, proc, cls, data, target): for t, c in data.iteritems():",
"in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data)",
"(t, c)) return POW.new(cls, (base, exp)) pow_number = pow def neg(self, cls, expr):",
"cls, expr): d = expr.data.copy() for key in d: d[key] = -d[key] return",
"d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self, Algebra,",
"coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result",
"term) * coeff if rhead is POW: base, exp = rdata if lhs==base:",
"POW: base, exp = rdata if lhs==base: return POW.new(cls, (lhs, exp + 1))",
"order, cache={}): key = (expr, symbol, order) result = cache.get(key) if result is",
"rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs)",
"c in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def",
"term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d,",
"expr, symbol, order, cache={}): key = (expr, symbol, order) result = cache.get(key) if",
"inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata,",
"algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra,",
"rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) +",
"coeff is not 1: new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls, df)",
"cache={}): key = (expr, symbol, order) result = cache.get(key) if result is not",
"exp = rdata if lhs==base: return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT,",
"'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()]",
"cls(NUMBER, 1) if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff",
"no cover else: return 'data must be dict instance but got %s' %",
"pow(self, cls, base, exp): if exp==0: return cls(NUMBER, 1) if exp==1: return base",
"{} result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.diff(cls,",
"return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr,",
"lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def algebra_mul_number(self, Algebra, lhs,",
"is not 1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff",
"dictonary should have more than 1 item' for item in data.iteritems(): msg =",
"def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r = [cls(TERM_COEFF, tc) for",
"term * coeff return r def term_coeff(self, cls, expr): term_coeff_dict = expr.data if",
"if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return",
"is NUMBER: return self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data ==",
"import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data)",
"result = cache.get(key) if result is not None: return result if result is",
"commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)), rhs)) def commutative_div(self, cls,",
"Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d: d[key] =",
"cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls,",
"SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is TERM_COEFF: term, coeff = d2",
"def sub_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls,",
"tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls,",
"rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs)",
"is BASE_EXP_DICT: dict_add_item(cls, data, t, c) else: self.add(cls, data, t * c, inplace=True)",
"lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs,",
"TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD: for op in d2: term,",
"not rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead is",
"rdata = rhs.pair if rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return",
"rhs.pair if rhead is NUMBER: if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls,",
"base, exp = rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1,",
"cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d)",
"= TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' % (item, msg)",
"data = {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return",
"b): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls,",
"= cache.get(key) if result is not None: return result if result is None:",
"term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def walk(self, func, cls, data, target):",
"lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs,",
"data, rhs, 1) else: dict_add_item(cls, data, rhs, 1) if inplace: return lhs return",
"is TERM_COEFF: rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra,",
"{lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff = rdata return number_div(cls, 1,",
"lhs, rhs, inplace): if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER,",
"d) def commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is",
"rcoeff = Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm, rcoeff = rhs,",
"if rhead is POW: base, exp = rdata if lhs==base: return POW.new(cls, (lhs,",
"NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is",
"data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r = cls(NUMBER, 0)",
"data) non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs,",
"inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d,",
"* c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data,",
"return cls(BASE_EXP_DICT, {lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1} for base,",
"1) cache[key] = result return result def apply(self, cls, data, func, args): result",
"cls, c.data, target) else: NUMBER.scan(proc, cls, c, target) proc(cls, self, data, target) def",
"+= term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff key1 = (expr, symbol,",
"rhs) def pow(self, cls, base, exp): if exp==0: return cls(NUMBER, 1) if exp==1:",
"def term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr,",
"if c==1: return t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number",
"= d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is BASE_EXP_DICT: dict_add_item(cls,",
"pow def neg(self, cls, expr): d = expr.data.copy() for key in d: d[key]",
"1: new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not",
"!= 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is SYMBOL: dict_add_item(cls, data,",
"rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff = rdata return",
"result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result def integrate_definite(self, cls,",
"if rhead is NUMBER: if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data,",
"rhead is NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs, rhs,",
"d) return func(cls, r.head, r.data, r) return func(cls, self, data, target) def scan(self,",
"elif rhead is TERM_COEFF: rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT: if",
"return base d = base.data if len(d)==1: t,c = dict_get_item(d) t,c = t**exp,",
"lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs,",
"rhead is BASE_EXP_DICT: data = {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data,",
"c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func, cls, c, c) if t1",
"Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata =",
"Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata =",
"term_coeff_dict): r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def",
"= ['TERM_COEFF_DICT'] from .base import heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module,",
"target): for t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if isinstance(c, Expr):",
"class TermCoeffDictHead(ArithmeticHead): def is_data_ok(self, cls, data): if type(data) is dict: n = len(data)",
"rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), rhs)",
"ADD: for op in d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff)",
"(expr, intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list =",
"for op in d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif",
"rhs): rhead, rdata = rhs.pair if rhead is NUMBER: return self.commutative_div_number(cls, lhs, rdata)",
"diff(self, cls, data, expr, symbol, order, cache={}): key = (expr, symbol, order) result",
"#if n<=1: # return 'data dictonary should have more than 1 item' for",
"rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead is",
"Pair(variables, {})) for term, coeff in data.iteritems(): r += term * coeff return",
"d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls,",
"lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1:",
"term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata,",
"return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number = pow def neg(self,",
"not c: flag = True add(cls, d, t1 * c1, inplace=True) if flag:",
"len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable:",
"dict_add_dict(cls, data, d2) elif h2 is ADD: for op in d2: term, coeff",
"expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data,",
"t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if",
"data, target) def diff(self, cls, data, expr, symbol, order, cache={}): key = (expr,",
"elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD: for op",
"lhs.data if rhead is ADD or rhead is EXP_COEFF_DICT or rhead is MUL",
"base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not 1: new_coeff *= coeff **",
"or h2 is NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`) elif h2",
"t,c = dict_get_item(d) t,c = t**exp, c**exp if t==1: return cls(NUMBER, c) if",
"is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is",
"init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients class TermCoeffDictHead(ArithmeticHead):",
"term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables is None:",
"q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s",
"rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy()",
"d = {} for t, c in expr.data.items(): self.add(cls, d, t.expand() * c,",
"if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data)",
"else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not 1: new_coeff *= coeff",
"heads, heads_precedence, ArithmeticHead, Pair from ..core import init_module, Expr init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module",
"init_module.import_heads() init_module.import_numbers() init_module.import_lowlevel_operations() @init_module def _init(module): from ..arithmetic.number_theory import multinomial_coefficients module.multinomial_coefficients = multinomial_coefficients",
"rhs): rhead, rdata = rhs.pair if rhead is NUMBER: if rdata==0: return rhs",
"data) def sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True)",
"if exp==1: return base d = base.data if len(d)==1: t,c = dict_get_item(d) t,c",
"term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff is not",
"rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs)",
"rhs.pair if rhead is NUMBER: if not rdata: return lhs rterm, rcoeff =",
"Algebra(NUMBER, 0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs",
"NUMBER.walk(func, cls, c, c) if t1 is not t or c1 is not",
"coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is SUB or h2",
"def add_number(self, cls, lhs, rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls,",
"[term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if",
"lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs,",
"= cls(NUMBER, 0) for term, coeff in data.iteritems(): r += term * coeff",
"if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2) elif h2 is SYMBOL:",
"rcoeff = rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff = rdata elif",
"exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls,",
"return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def",
"return r def term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict)",
"term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls, data, expr, variables=None): if variables",
"lhs) d = ldata.copy() term_coeff_dict_add_item(Algebra, d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return",
"return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) def",
"rhs): if rhs==0: return lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs)",
"for t, c in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls,",
"def diff(self, cls, data, expr, symbol, order, cache={}): key = (expr, symbol, order)",
"key = (expr, symbol, order) result = cache.get(key) if result is not None:",
"cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for term, coeff in",
"in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls, item, allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s'",
"is not c: flag = True add(cls, d, t1 * c1, inplace=True) if",
"term.head.diff(cls, term.data, term, symbol, order, cache=cache) * coeff key1 = (expr, symbol, 1)",
"cls, data): if type(data) is dict: n = len(data) #if n<=1: # return",
"EXP_COEFF_DICT or rhead is MUL or rhead is NEG: rhs = rhead.to_TERM_COEFF_DICT(Algebra, rdata,",
"= {} rd = 0 for t,c in lhs.data.items(): c /= d2 q,",
"{})) for term, coeff in data.iteritems(): r += term * coeff return r",
"data.iteritems(): result += term.head.apply(cls, term.data, term, args) * coeff return result def integrate_indefinite(self,",
"if inplace: data = lhs else: data = lhs.data.copy() h2, d2 = rhs.pair",
"(lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is SYMBOL or",
"cls, data, expr, symbol, order, cache={}): key = (expr, symbol, order) result =",
"coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a, b) * coeff",
"term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s,",
"ldata = lhs.data if rhead is ADD or rhead is EXP_COEFF_DICT or rhead",
"if h2 is NUMBER: if d2 != 0: dict_add_item(cls, data, cls(NUMBER, 1), d2)",
"NUMBER: if rdata==0: return rhs data = lhs.data.copy() dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls,",
"= expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs,",
"if t==1: return cls(NUMBER, c) if c==1: return t return cls(TERM_COEFF, (t, c))",
"cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff = rdata return number_div(cls,",
"coeff) * (lhs / term) if rhead is POW: base, exp = rdata",
"data = rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is",
"c = divmod(c, d3) if c: d[t] = c rd += q s",
"is SUB or h2 is NEG or h2 is POS: raise NotImplementedError(`self, rhs.pair`)",
"allow_number_term=True) if msg: return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no cover",
"in data.iteritems(): r += term * coeff return r def to_ADD(self, Algebra, data,",
"d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d = {}",
"NUMBER: return self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs, rhs, inplace) TERM_COEFF_DICT",
"new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r =",
"def sub(self, cls, lhs, rhs): d = lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return",
"result def algebra_pos(self, Algebra, expr): return expr def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'):",
"* coeff return r def term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1:",
"if exp==0: return cls(NUMBER, 1) if exp==1: return base d = base.data if",
"msg: return 'TERM_COEFF data=%s: %s' % (item, msg) #pragma: no cover else: return",
"rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if rhs==0: return lhs",
"lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL, [lhs, Algebra(NUMBER, rhs)]) def",
"for term, coeff in data.iteritems(): result += term.head.apply(cls, term.data, term, args) * coeff",
"return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number",
"lhs==base: return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead",
"for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for",
"data): r = cls(NUMBER, 0) for term, coeff in data.iteritems(): r += term",
"return cls(NUMBER, 1) if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for term,",
"is TERM_COEFF: term, coeff = rdata return (lhs * term) * coeff if",
"df, base, exp*e_i) if coeff is not 1: new_coeff *= coeff ** e_i",
"cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs):",
"expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return expr, 1 def inplace_add(self, cls, lhs, rhs):",
"rd += q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd`",
"= [(term.base_exp(), coeff) for term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d",
"non_commutative_mul_number = commutative_mul_number def commutative_rdiv_number(self, cls, lhs, rhs): return term_coeff_new(cls, (cls(POW, (lhs, -1)),",
"return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return Algebra(MUL,",
"inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if intexp<0: return cls(POW,",
"lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra,",
"n<=1: # return 'data dictonary should have more than 1 item' for item",
"return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra,",
"= lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data)",
"coeff = rdata return number_div(cls, 1, coeff) * (lhs / term) if rhead",
"in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT, d) return Algebra(NEG, expr) def algebra_add_number(self,",
"d, Algebra(NUMBER, 1), rhs) return term_coeff_dict_new(Algebra, d) def algebra_add(self, Algebra, lhs, rhs, inplace):",
"rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata) return term_coeff_dict(Algebra, lhs) d =",
"# return 'data dictonary should have more than 1 item' for item in",
"c)) return POW.new(cls, (base, exp)) pow_number = pow def neg(self, cls, expr): d",
"commutative_mul_number(self, cls, lhs, rhs): if rhs==0: return cls(NUMBER, 0) data = lhs.data.copy() dict_mul_value(cls,",
"inplace): if Algebra.algebra_options.get('evaluate_addition'): if not rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs",
"1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or rhead is APPLY:",
"data): if type(data) is dict: n = len(data) #if n<=1: # return 'data",
"if rhead is TERM_COEFF: term, coeff = rdata return number_div(cls, 1, coeff) *",
"expr, x, a, b): result = cls(NUMBER, 0) for term, coeff in data.iteritems():",
"expr) def algebra_add_number(self, Algebra, lhs, rhs, inplace): if not rhs: return lhs if",
"return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is TERM_COEFF: term, coeff = rdata return",
"* (lhs / term) if rhead is POW: base, exp = rdata if",
"dict_add_item(cls, data, t, c) else: self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls,",
"self, data, target) def scan(self, proc, cls, data, target): for t, c in",
"rdata return (lhs * term) * coeff if rhead is POW: base, exp",
"rhead is SYMBOL or rhead is APPLY: return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead",
"[s, Algebra(NUMBER, d3)]) + rd return Algebra(DIV, [lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra,",
"in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls, df, base, exp) if coeff",
"c: d[t] = c rd += q s = term_coeff_dict_new(Algebra, d) if rhs==d2:",
"is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is not None: d =",
"add(self, cls, lhs, rhs, inplace=False): if inplace: data = lhs else: data =",
"variables=None): if variables is None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r =",
"not 1: new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d,",
"target) proc(cls, self, data, target) def diff(self, cls, data, expr, symbol, order, cache={}):",
"if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls,",
"return expr, 1 def inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data = lhs.data",
"term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs return super(type(self), self).algebra_add(Algebra, lhs,",
"is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self,",
"base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self, cls, lhs, rhs) def pow(self, cls, base, exp): if",
"term, coeff in expr.data.items()] mdata = multinomial_coefficients(len(term_coeff_list), intexp) d = {} for e,c",
"should have more than 1 item' for item in data.iteritems(): msg = TERM_COEFF.is_data_ok(cls,",
"rterm, rcoeff = rdata elif rhead is TERM_COEFF_DICT: if inplace: term_coeff_dict_add_dict(Algebra, ldata, rdata)",
"add(cls, d, t1 * c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d) return",
"cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs,",
"r = [cls(TERM_COEFF, tc) for tc in term_coeff_dict.items()] return ADD.data_to_str_and_precedence(cls, r) def new(self,",
"lhs data = lhs.data.copy() term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def",
"lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1})",
"new_coeff *= coeff else: base_exp_dict_add_item(cls, df, base, exp*e_i) if coeff is not 1:",
"no cover return def __repr__(self): return 'TERM_COEFF_DICT' def data_to_str_and_precedence(self, cls, term_coeff_dict): r =",
"= c rd += q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh,",
"if rhead is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER, 1) return cls(BASE_EXP_DICT,",
"in d: d[key] = -d[key] return cls(TERM_COEFF_DICT, d) def expand(self, cls, expr): d",
"term, coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD:",
"term.head.apply(cls, term.data, term, args) * coeff return result def integrate_indefinite(self, cls, data, expr,",
"data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for term_coeff in data.iteritems()]) def to_EXP_COEFF_DICT(self, cls,",
"None: d = d2.copy() del d[c] t = BASE_EXP_DICT.new(cls, d) if t.head is",
"cls, data, expr, x, a, b): result = cls(NUMBER, 0) for term, coeff",
"POW.new(cls, (base, exp)) pow_number = pow def neg(self, cls, expr): d = expr.data.copy()",
"expr, intexp): if intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1)",
"def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is",
"data, rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff = rdata",
"new_coeff *= coeff ** e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff)",
"= rhs.pair if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD or rhead",
"rd = 0 for t,c in lhs.data.items(): c /= d2 q, c =",
"not rhs: return Algebra(NUMBER, 0) if rhs==1: return lhs if inplace: term_coeff_dict_mul_value(Algebra, lhs.data,",
"lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm, rcoeff",
"d, rterm, rcoeff) return term_coeff_dict_new(Algebra, d) else: return TERM_COEFF_DICT.to_ADD(Algebra, lhs.data, lhs) + rhs",
"t,c = t**exp, c**exp if t==1: return cls(NUMBER, c) if c==1: return t",
"rhs, inplace): rhead, rdata = rhs.pair if rhead is NUMBER: return self.algebra_mul_number(Algebra, lhs,",
"r def term_coeff(self, cls, expr): term_coeff_dict = expr.data if len(term_coeff_dict)==1: return dict_get_item(term_coeff_dict) return",
"self.algebra_div_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_div(Algebra, lhs, rhs, inplace) TERM_COEFF_DICT = TermCoeffDictHead()",
"scan(self, proc, cls, data, target): for t, c in data.iteritems(): t.head.scan(proc, cls, t.data,",
"elif rhead is SYMBOL: rterm, rcoeff = rhs, 1 elif rhead is TERM_COEFF:",
"d, rdata) return term_coeff_dict_new(Algebra, d) else: return super(type(self), self).algebra_add(Algebra, lhs, rhs, inplace) if",
"= len(data) #if n<=1: # return 'data dictonary should have more than 1",
"self.commutative_div_number(cls, lhs, rdata) if rhead is TERM_COEFF_DICT: if lhs.data == rdata: return cls(NUMBER,",
"inplace_add(self, cls, lhs, rhs): if lhs.is_writable: data = lhs.data else: data = lhs.data.copy()",
"NotImplementedError(`self, rhs.pair`) elif h2 is BASE_EXP_DICT: c = base_exp_dict_get_coefficient(cls, d2) if c is",
"(item, msg) #pragma: no cover else: return 'data must be dict instance but",
"= lhs.data.copy() self.add(cls, d, -rhs, inplace=True) return term_coeff_dict_new(cls, d) def commutative_mul(self, cls, lhs,",
"rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER, 1), rhs) return",
"for e_i, ((base, exp), coeff) in zip(e, term_coeff_list): if e_i: if e_i==1: base_exp_dict_add_item(cls,",
"def algebra_neg(self, Algebra, expr): if Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d:",
"Algebra.algebra_options.get('evaluate_addition'): d = expr.data.copy() for key in d: d[key] = -d[key] return Algebra(TERM_COEFF_DICT,",
"= rhs.pair if rhead is NUMBER: if rdata==0: return rhs data = lhs.data.copy()",
"return POW.new(cls, (lhs, exp + 1)) return cls(BASE_EXP_DICT, {lhs:1, base:exp}) if rhead is",
"commutative_mul(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: if",
"term, x) * coeff return result def integrate_definite(self, cls, data, expr, x, a,",
"key1 = (expr, symbol, 1) cache[key] = result return result def apply(self, cls,",
"c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if intexp<0: return",
"data, rhs, 1) if inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls,",
"h2 is ADD: for op in d2: term, coeff = op.term_coeff() dict_add_item(cls, data,",
"rhead, rdata = rhs.pair if rhead is NUMBER: if rdata==0: return rhs data",
"type(data) is dict: n = len(data) #if n<=1: # return 'data dictonary should",
"None: r = cls(EXP_COEFF_DICT, Pair((), {})) else: r = cls(EXP_COEFF_DICT, Pair(variables, {})) for",
"term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is SUB or",
"t, c in expr.data.items(): self.add(cls, d, t.expand() * c, inplace=True) return term_coeff_dict_new(cls, d)",
"if not rhs: return lhs if inplace: term_coeff_dict_add_item(Algebra, lhs.data, Algebra(NUMBER, 1), rhs) return",
"term.data, term, x, a, b) * coeff return result def algebra_pos(self, Algebra, expr):",
"0) for term, coeff in data.iteritems(): result += term.head.apply(cls, term.data, term, args) *",
"lhs else: data = lhs.data.copy() h2, d2 = rhs.pair if h2 is NUMBER:",
"return func(cls, self, data, target) def scan(self, proc, cls, data, target): for t,",
"return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) if rhead is TERM_COEFF_DICT: if rdata==lhs.data: return cls(POW, (lhs,",
"0) for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data, term, x, a,",
"cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: if rdata==0:",
"c = base_exp_dict_get_coefficient(cls, d2) if c is not None: d = d2.copy() del",
"if rhead is ADD: return cls(BASE_EXP_DICT, {lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs)",
"def add(self, cls, lhs, rhs, inplace=False): if inplace: data = lhs else: data",
"integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER, 0) for term, coeff in",
"inplace=True) else: dict_add_item(cls, data, rhs, 1) else: dict_add_item(cls, data, rhs, 1) if inplace:",
"coeff return r def to_ADD(self, Algebra, data, expr): return add_new(Algebra, [term_coeff_new(Algebra, term_coeff) for",
"d3 = rhs / d2 d = {} rd = 0 for t,c",
"intexp<0: return cls(POW, (expr, intexp)) if intexp==0: return cls(NUMBER, 1) if intexp==1: return",
"in data.iteritems(): t1 = t.head.walk(func, cls, t.data, t) if isinstance(c, Expr): c1 =",
"proc, cls, data, target): for t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target)",
"s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert rd==0,`lsh, rhs, s,rd` return s return",
"in d2: term, coeff = op.term_coeff() dict_add_item(cls, data, term, coeff) elif h2 is",
"base.data if len(d)==1: t,c = dict_get_item(d) t,c = t**exp, c**exp if t==1: return",
"def reevaluate(self, cls, data): r = cls(NUMBER, 0) for term, coeff in data.iteritems():",
"Algebra(NUMBER, 1), rdata elif rhead is SYMBOL: rterm, rcoeff = rhs, 1 elif",
"d[t] = c rd += q s = term_coeff_dict_new(Algebra, d) if rhs==d2: assert",
"result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result += term.head.integrate_definite(cls, term.data,",
"inplace: return lhs return term_coeff_dict_new(cls, data) def add_number(self, cls, lhs, rhs): if rhs==0:",
"func, args): result = cls(NUMBER, 0) for term, coeff in data.iteritems(): result +=",
"(expr, symbol, order) result = cache.get(key) if result is not None: return result",
"c) else: self.add(cls, data, t * c, inplace=True) else: dict_add_item(cls, data, rhs, 1)",
"is NUMBER: return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace)",
"* c, inplace=True) return term_coeff_dict_new(cls, d) def expand_intpow(self, cls, expr, intexp): if intexp<0:",
"+= term.head.integrate_indefinite(cls, term.data, term, x) * coeff return result def integrate_definite(self, cls, data,",
"ADD.data_to_str_and_precedence(cls, r) def new(self, cls, data, evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls,",
"c1 = c.head.walk(func, cls, c.data, c) else: c1 = NUMBER.walk(func, cls, c, c)",
"cls, data, target): for t, c in data.iteritems(): t.head.scan(proc, cls, t.data, target) if",
"c1, inplace=True) if flag: r = term_coeff_dict_new(cls, d) return func(cls, r.head, r.data, r)",
"if inplace: term_coeff_dict_mul_value(Algebra, lhs.data, rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs)",
"coeff) elif h2 is TERM_COEFF_DICT: dict_add_dict(cls, data, d2) elif h2 is ADD: for",
"c==1: return t return cls(TERM_COEFF, (t, c)) return POW.new(cls, (base, exp)) pow_number =",
"if result is not None: return result if result is None: d =",
"inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs",
"cls, base, exp): if exp==0: return cls(NUMBER, 1) if exp==1: return base d",
"BASE_EXP_DICT: data = rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead",
"c, c) if t1 is not t or c1 is not c: flag",
"data = lhs.data else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls,",
"1), rhs) return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if rhs==0: return",
"return self.algebra_mul_number(Algebra, lhs, rdata, inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self,",
"cls(NUMBER, 1) return cls(BASE_EXP_DICT, {lhs:1, rhs:-1}) if rhead is SYMBOL or rhead is",
"dict_add_item(cls, data, term, coeff) elif h2 is SUB or h2 is NEG or",
"/= d2 q, c = divmod(c, d3) if c: d[t] = c rd",
"SYMBOL: rterm, rcoeff = rhs, 1 elif rhead is TERM_COEFF: rterm, rcoeff =",
"{lhs:1, base:-exp}) if rhead is BASE_EXP_DICT: data = {lhs:1} for base, exp in",
"base, exp in rdata.iteritems(): base_exp_dict_add_item(cls, data, base, -exp) return base_exp_dict_new(cls, data) return ArithmeticHead.commutative_div(self,",
"evaluate=True): return term_coeff_dict_new(cls, data) def reevaluate(self, cls, data): r = cls(NUMBER, 0) for",
"commutative_div(self, cls, lhs, rhs): rhead, rdata = rhs.pair if rhead is NUMBER: return",
"if rhead is BASE_EXP_DICT: data = {lhs:1} for base, exp in rdata.iteritems(): base_exp_dict_add_item(cls,",
"for term, coeff in data.iteritems(): result += term.head.integrate_indefinite(cls, term.data, term, x) * coeff",
"1), d2) elif h2 is SYMBOL: dict_add_item(cls, data, rhs, 1) elif h2 is",
"term_coeff_dict_add_item(cls, data, cls(NUMBER, 1), -rhs) return term_coeff_dict_new(cls, data) def sub(self, cls, lhs, rhs):",
"else: data = lhs.data.copy() self.add(cls, data, rhs, inplace=True) return term_coeff_dict_new(cls, data) def add(self,",
"rdata.copy() dict_add_item(cls, data, lhs, 1) return BASE_EXP_DICT.new(cls, data) if rhead is ADD: return",
"lhs.data, Algebra(NUMBER, 1), rhs) return term_coeff_dict(Algebra, lhs) d = lhs.data.copy() term_coeff_dict_add_item(Algebra, d, Algebra(NUMBER,",
"exp = rdata if lhs==base: return pow_new(cls, (lhs, 1-exp)) return cls(BASE_EXP_DICT, {lhs:1, base:-exp})",
"{lhs:1, rhs:1}) return ArithmeticHead.commutative_mul(self, cls, lhs, rhs) def commutative_mul_number(self, cls, lhs, rhs): if",
"def algebra_mul(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is",
"rd==0,`lsh, rhs, s,rd` return s return Algebra(DIV, [s, Algebra(NUMBER, d3)]) + rd return",
"lhs d1 = gcd(*lhs.data.values()) d2 = gcd(d1, rhs) d3 = rhs / d2",
"e_i new_term = base_exp_dict_new(cls, df) term_coeff_dict_add_item(cls, d, new_term, new_coeff) return term_coeff_dict_new(cls, d) def",
"= lhs else: data = lhs.data.copy() h2, d2 = rhs.pair if h2 is",
"if Algebra.algebra_options.get('evaluate_addition'): ldata = lhs.data if rhead is ADD or rhead is EXP_COEFF_DICT",
"dict_mul_value(cls, data, rdata) return term_coeff_dict_new(cls, data) if rhead is TERM_COEFF: term, coeff =",
"inplace) if inplace: term_coeff_dict_add_item(Algebra, ldata, rterm, rcoeff) return term_coeff_dict(Algebra, lhs) d = ldata.copy()",
"algebra_div_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('evaluate_addition'): if rhs==1: return lhs d1 =",
"return term_coeff_dict_new(cls, data) def sub_number(self, cls, lhs, rhs): if rhs==0: return lhs data",
"def neg(self, cls, expr): d = expr.data.copy() for key in d: d[key] =",
"[lhs, Algebra(NUMBER, rhs)]) def algebra_div(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair",
"if intexp==1: return expr term_coeff_list = [(term.base_exp(), coeff) for term, coeff in expr.data.items()]",
"inplace) return super(type(self), self).algebra_mul(Algebra, lhs, rhs, inplace) def algebra_div_number(self, Algebra, lhs, rhs, inplace):",
"NUMBER: if not rdata: return lhs rterm, rcoeff = Algebra(NUMBER, 1), rdata elif",
"data = lhs.data.copy() dict_mul_value(cls, data, rhs) return cls(self, data) non_commutative_mul_number = commutative_mul_number def",
"rhs) return lhs d = lhs.data.copy() term_coeff_dict_mul_value(Algebra, d, rhs) return Algebra(TERM_COEFF_DICT, d) return",
"cls, lhs, rhs) def pow(self, cls, base, exp): if exp==0: return cls(NUMBER, 1)",
"def integrate_indefinite(self, cls, data, expr, x): result = cls(NUMBER, 0) for term, coeff"
] |
[
"the user platform: the platform they are on (epic / psn / xbl)",
"the name of the user platform: the platform they are on (epic /",
"fortnite players stats ----- name: the name of the user platform: the platform",
"xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends a request for",
"import AsyncTTL ''' ----- Get fortnite players stats ----- name: the name of",
"----- name: the name of the user platform: the platform they are on",
"<gh_stars>1-10 import requests from cache import AsyncTTL ''' ----- Get fortnite players stats",
"name: the name of the user platform: the platform they are on (epic",
"AsyncTTL ''' ----- Get fortnite players stats ----- name: the name of the",
"platform): # Sends a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json() # Retuns",
"@AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends a request for the data",
"the platform they are on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024)",
"def get_player_stats(name, platform): # Sends a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json()",
"are on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name,",
"''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends a request for the",
"user platform: the platform they are on (epic / psn / xbl) '''",
"requests from cache import AsyncTTL ''' ----- Get fortnite players stats ----- name:",
"of the user platform: the platform they are on (epic / psn /",
"get_player_stats(name, platform): # Sends a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json() #",
"async def get_player_stats(name, platform): # Sends a request for the data data =",
"name of the user platform: the platform they are on (epic / psn",
"# Sends a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json() # Retuns it",
"cache import AsyncTTL ''' ----- Get fortnite players stats ----- name: the name",
"''' ----- Get fortnite players stats ----- name: the name of the user",
"----- Get fortnite players stats ----- name: the name of the user platform:",
"maxsize=1024) async def get_player_stats(name, platform): # Sends a request for the data data",
"on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform):",
"platform: the platform they are on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120,",
"/ psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends",
"import requests from cache import AsyncTTL ''' ----- Get fortnite players stats -----",
"/ xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends a request",
"from cache import AsyncTTL ''' ----- Get fortnite players stats ----- name: the",
"a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json() # Retuns it return data",
"platform they are on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async",
"Get fortnite players stats ----- name: the name of the user platform: the",
"stats ----- name: the name of the user platform: the platform they are",
"psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): # Sends a",
"players stats ----- name: the name of the user platform: the platform they",
"they are on (epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def",
"(epic / psn / xbl) ''' @AsyncTTL(time_to_live=120, maxsize=1024) async def get_player_stats(name, platform): #",
"Sends a request for the data data = requests.get(f\"https://fortnite-api.com/v1/stats/br/v2?name={name}&accountType={platform}&image=all\").json() # Retuns it return"
] |
[
"option) any later version. #This program is distributed in the hope that it",
"the License, or (at your option) any later version. #This program is distributed",
"enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE,",
"print \"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS,",
"software; you can redistribute it and/or #modify it under the terms of the",
"(at your option) any later version. #This program is distributed in the hope",
"i2c_addr = 0x54 # fixed i2c address of SN3218 ic bus = None",
"Public License #along with this program; if not, write to the Free Software",
"free software; you can redistribute it and/or #modify it under the terms of",
"by <NAME> based on code from Pimoroni #This program is free software; you",
"#print \"update piglow pwm done\" def write_i2c(self, reg_addr, value): if not isinstance(value, list):",
"import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01",
"<reponame>davidramirezm30/scratch-orangepi #!/usr/bin/env python # sgh_PiGlow - control PiGlow LEDS via ScratchGPIO. #Copyright (C)",
"the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"= smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds()",
"CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr =",
"# fixed i2c address of SN3218 ic bus = None def __init__(self, i2c_bus=1):",
"code from Pimoroni #This program is free software; you can redistribute it and/or",
"is distributed in the hope that it will be useful, #but WITHOUT ANY",
"02110-1301, USA. Version = '0.0.3' # 1Jan13 #try and inport smbus but don't",
"bus = None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print",
"by the Free Software Foundation; either version 2 #of the License, or (at",
"done\" def write_i2c(self, reg_addr, value): if not isinstance(value, list): value = [value]; try:",
"import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13",
"= '0.0.3' # 1Jan13 #try and inport smbus but don't worry if not",
"write_i2c(self, reg_addr, value): if not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr,",
"= [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr,",
"the terms of the GNU General Public License #as published by the Free",
"(C) 2013 by <NAME> based on code from Pimoroni #This program is free",
"of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public",
"self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18):",
"Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Version",
"smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE",
"try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES =",
"* 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def write_i2c(self,",
"enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] *",
"is free software; you can redistribute it and/or #modify it under the terms",
"#This program is free software; you can redistribute it and/or #modify it under",
"\"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds \" print \"complete\"",
"\"enabled output\" self.enable_leds() print \"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01)",
"terms of the GNU General Public License #as published by the Free Software",
"try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) ####",
"smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds \"",
"print \"enabled output\" self.enable_leds() print \"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT,",
"but don't worry if not installed import subprocess try: import smbus except: pass",
"value): if not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except",
"<NAME> based on code from Pimoroni #This program is free software; you can",
"Foundation; either version 2 #of the License, or (at your option) any later",
"\"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self,",
"in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without",
"#!/usr/bin/env python # sgh_PiGlow - control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013",
"Software Foundation; either version 2 #of the License, or (at your option) any",
"Boston, MA 02110-1301, USA. Version = '0.0.3' # 1Jan13 #try and inport smbus",
"via ScratchGPIO. #Copyright (C) 2013 by <NAME> based on code from Pimoroni #This",
"it under the terms of the GNU General Public License #as published by",
"\"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus)",
"GNU General Public License #as published by the Free Software Foundation; either version",
"and inport smbus but don't worry if not installed import subprocess try: import",
"ic bus = None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus",
"pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16",
"0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update",
"print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print",
"#GNU General Public License for more details. #You should have received a copy",
"address of SN3218 ic bus = None def __init__(self, i2c_bus=1): print \"PiGlow init\"",
"program is distributed in the hope that it will be useful, #but WITHOUT",
"class PiGlow: i2c_addr = 0x54 # fixed i2c address of SN3218 ic bus",
"#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License",
"it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty",
"if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth",
"smbus but don't worry if not installed import subprocess try: import smbus except:",
"CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54 # fixed i2c address of",
"def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values)",
"= 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54",
"not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect',",
"reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) #### end PiGlow",
"be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY",
"Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Version = '0.0.3' # 1Jan13",
"Street, Fifth Floor, Boston, MA 02110-1301, USA. Version = '0.0.3' # 1Jan13 #try",
"0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow",
"value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) #### end PiGlow ###############################################################",
"to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA",
"your option) any later version. #This program is distributed in the hope that",
"with this program; if not, write to the Free Software #Foundation, Inc., 51",
"Fifth Floor, Boston, MA 02110-1301, USA. Version = '0.0.3' # 1Jan13 #try and",
"subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES",
"don't worry if not installed import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT",
"any later version. #This program is distributed in the hope that it will",
"of SN3218 ic bus = None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus",
"def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm",
"it and/or #modify it under the terms of the GNU General Public License",
"#as published by the Free Software Foundation; either version 2 #of the License,",
"published by the Free Software Foundation; either version 2 #of the License, or",
"1Jan13 #try and inport smbus but don't worry if not installed import subprocess",
"# 1Jan13 #try and inport smbus but don't worry if not installed import",
"copy of the GNU General Public License #along with this program; if not,",
"redistribute it and/or #modify it under the terms of the GNU General Public",
"= 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow:",
"print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds \" print",
"PiGlow: i2c_addr = 0x54 # fixed i2c address of SN3218 ic bus =",
"self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\",",
"ScratchGPIO. #Copyright (C) 2013 by <NAME> based on code from Pimoroni #This program",
"self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled",
"isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y',",
"the #GNU General Public License for more details. #You should have received a",
"0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54 #",
"#but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS",
"on code from Pimoroni #This program is free software; you can redistribute it",
"can redistribute it and/or #modify it under the terms of the GNU General",
"PURPOSE. See the #GNU General Public License for more details. #You should have",
"def write_i2c(self, reg_addr, value): if not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr,",
"PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME> based on code from",
"General Public License #as published by the Free Software Foundation; either version 2",
"= None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus",
"useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or",
"values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def write_i2c(self, reg_addr, value): if",
"FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more",
"\"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF,",
"self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds \" print \"complete\" def enable_output(self):",
"None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus",
"self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF)",
"#Copyright (C) 2013 by <NAME> based on code from Pimoroni #This program is",
"GNU General Public License #along with this program; if not, write to the",
"init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print",
"#This program is distributed in the hope that it will be useful, #but",
"either version 2 #of the License, or (at your option) any later version.",
"print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus =",
"Version = '0.0.3' # 1Jan13 #try and inport smbus but don't worry if",
"the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,",
"reg_addr, value): if not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value)",
"ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A",
"write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,",
"control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME> based on code",
"- control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME> based on",
"hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the",
"self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def write_i2c(self, reg_addr, value):",
"= 0x16 class PiGlow: i2c_addr = 0x54 # fixed i2c address of SN3218",
"that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied",
"self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) #### end",
"the Free Software Foundation; either version 2 #of the License, or (at your",
"under the terms of the GNU General Public License #as published by the",
"have received a copy of the GNU General Public License #along with this",
"#self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\"",
"warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General",
"= 0x54 # fixed i2c address of SN3218 ic bus = None def",
"the GNU General Public License #along with this program; if not, write to",
"i2c address of SN3218 ic bus = None def __init__(self, i2c_bus=1): print \"PiGlow",
"or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for",
"#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Version =",
"MA 02110-1301, USA. Version = '0.0.3' # 1Jan13 #try and inport smbus but",
"inport smbus but don't worry if not installed import subprocess try: import smbus",
"Free Software Foundation; either version 2 #of the License, or (at your option)",
"PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should",
"Pimoroni #This program is free software; you can redistribute it and/or #modify it",
"0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54 # fixed i2c address",
"more details. #You should have received a copy of the GNU General Public",
"Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
"License #as published by the Free Software Foundation; either version 2 #of the",
"[value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value)",
"should have received a copy of the GNU General Public License #along with",
"General Public License #along with this program; if not, write to the Free",
"pwm done\" def write_i2c(self, reg_addr, value): if not isinstance(value, list): value = [value];",
"a copy of the GNU General Public License #along with this program; if",
"of the GNU General Public License #along with this program; if not, write",
"from Pimoroni #This program is free software; you can redistribute it and/or #modify",
"self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds \" print \"complete\" def",
"0xFF) #print \"update piglow pwm done\" def write_i2c(self, reg_addr, value): if not isinstance(value,",
"Public License for more details. #You should have received a copy of the",
"sgh_PiGlow - control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME> based",
"i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus",
"except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE =",
"LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME> based on code from Pimoroni",
"program is free software; you can redistribute it and/or #modify it under the",
"#try and inport smbus but don't worry if not installed import subprocess try:",
"worry if not installed import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT =",
"General Public License for more details. #You should have received a copy of",
"[0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print",
"not installed import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS",
"\" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF])",
"the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even",
"__init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus)",
"you can redistribute it and/or #modify it under the terms of the GNU",
"later version. #This program is distributed in the hope that it will be",
"#along with this program; if not, write to the Free Software #Foundation, Inc.,",
"program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street,",
"python # sgh_PiGlow - control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by",
"version. #This program is distributed in the hope that it will be useful,",
"2013 by <NAME> based on code from Pimoroni #This program is free software;",
"0x16 class PiGlow: i2c_addr = 0x54 # fixed i2c address of SN3218 ic",
"without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"of the GNU General Public License #as published by the Free Software Foundation;",
"License, or (at your option) any later version. #This program is distributed in",
"0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr",
"or (at your option) any later version. #This program is distributed in the",
"leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF,",
"18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def write_i2c(self, reg_addr,",
"implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU",
"i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output()",
"based on code from Pimoroni #This program is free software; you can redistribute",
"\"update piglow pwm done\" def write_i2c(self, reg_addr, value): if not isinstance(value, list): value",
"License #along with this program; if not, write to the Free Software #Foundation,",
"print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def",
"self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def write_i2c(self, reg_addr, value): if not",
"SN3218 ic bus = None def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus =",
"if not isinstance(value, list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError:",
"for more details. #You should have received a copy of the GNU General",
"= i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus",
"list): value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0'])",
"installed import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS =",
"2 #of the License, or (at your option) any later version. #This program",
"fixed i2c address of SN3218 ic bus = None def __init__(self, i2c_bus=1): print",
"#You should have received a copy of the GNU General Public License #along",
"received a copy of the GNU General Public License #along with this program;",
"values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\" def",
"FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details.",
"if not installed import subprocess try: import smbus except: pass CMD_ENABLE_OUTPUT = 0x00",
"WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR",
"#modify it under the terms of the GNU General Public License #as published",
"0x54 # fixed i2c address of SN3218 ic bus = None def __init__(self,",
"USA. Version = '0.0.3' # 1Jan13 #try and inport smbus but don't worry",
"= smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print \"enabled leds",
"distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY;",
"#of the License, or (at your option) any later version. #This program is",
"Floor, Boston, MA 02110-1301, USA. Version = '0.0.3' # 1Jan13 #try and inport",
"See the #GNU General Public License for more details. #You should have received",
"self.enable_leds() print \"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self):",
"License for more details. #You should have received a copy of the GNU",
"output\" self.enable_leds() print \"enabled leds \" print \"complete\" def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def",
"# sgh_PiGlow - control PiGlow LEDS via ScratchGPIO. #Copyright (C) 2013 by <NAME>",
"def enable_output(self): self.write_i2c(CMD_ENABLE_OUTPUT, 0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0]",
"CMD_ENABLE_OUTPUT = 0x00 CMD_ENABLE_LEDS = 0x13 CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class",
"= 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54 # fixed i2c",
"WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Version = '0.0.3' #",
"smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled output\" self.enable_leds() print",
"update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES, values) self.write_i2c(CMD_UPDATE, 0xFF) #print \"update piglow pwm done\"",
"this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin",
"even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"details. #You should have received a copy of the GNU General Public License",
"Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Version = '0.0.3'",
"\"i2cbus:\",self.i2c_bus #self.bus = smbus.SMBus(i2c_bus) self.bus = smbus.SMBus(i2c_bus) print \"self.bus:\", self.bus self.enable_output() print \"enabled",
"not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor,",
"0x01) def enable_leds(self): self.write_i2c(CMD_ENABLE_LEDS, [0xFF, 0xFF, 0xFF]) def update_pwm_values(self, values=[0] * 18): self.write_i2c(CMD_SET_PWM_VALUES,",
"value = [value]; try: self.bus.write_i2c_block_data(self.i2c_addr, reg_addr, value) except IOError: subprocess.call(['i2cdetect', '-y', '0']) self.bus.write_i2c_block_data(self.i2c_addr,",
"A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You",
"def __init__(self, i2c_bus=1): print \"PiGlow init\" self.i2c_bus = i2c_bus print \"i2cbus:\",self.i2c_bus #self.bus =",
"the GNU General Public License #as published by the Free Software Foundation; either",
"Public License #as published by the Free Software Foundation; either version 2 #of",
"version 2 #of the License, or (at your option) any later version. #This",
"piglow pwm done\" def write_i2c(self, reg_addr, value): if not isinstance(value, list): value =",
"and/or #modify it under the terms of the GNU General Public License #as",
"will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of",
"'0.0.3' # 1Jan13 #try and inport smbus but don't worry if not installed",
"CMD_SET_PWM_VALUES = 0x01 CMD_UPDATE = 0x16 class PiGlow: i2c_addr = 0x54 # fixed"
] |
[
"# auth.py import os import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username,",
"return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in authentication_credentials and password_hash == authentication_credentials[username]",
"or password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in authentication_credentials",
"import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None or",
"= json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None or password is None:",
"<filename>web/src/auth.py # auth.py import os import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def",
"authenticate(username, password): if username is None or password is None: return False password_hash",
"json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None or password is None: return",
"hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None or password",
"password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in authentication_credentials and",
"os import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username",
"None or password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in",
"import os import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if",
"None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in authentication_credentials and password_hash ==",
"authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None or password is",
"is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username in authentication_credentials and password_hash",
"def authenticate(username, password): if username is None or password is None: return False",
"if username is None or password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest()",
"is None or password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return username",
"password): if username is None or password is None: return False password_hash =",
"json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is None",
"auth.py import os import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password):",
"import json import hashlib authentication_credentials = json.loads(os.environ['AUTHENTICATION_CREDENTIALS']) def authenticate(username, password): if username is",
"username is None or password is None: return False password_hash = hashlib.sha512(password.encode()).hexdigest() return"
] |
[
"0 self.children = {} if children is None else children def __repr__(self): return",
"is None else children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" % (",
"as np class Node: def __init__(self, value=-np.inf, children=None): self.value = value self.visits =",
"else children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" % ( self.value, self.visits,",
"children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" % ( self.value, self.visits, len(self.children),",
"value=-np.inf, children=None): self.value = value self.visits = 0 self.children = {} if children",
"np class Node: def __init__(self, value=-np.inf, children=None): self.value = value self.visits = 0",
"Node: def __init__(self, value=-np.inf, children=None): self.value = value self.visits = 0 self.children =",
"def __init__(self, value=-np.inf, children=None): self.value = value self.visits = 0 self.children = {}",
"if children is None else children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\"",
"children=None): self.value = value self.visits = 0 self.children = {} if children is",
"{} if children is None else children def __repr__(self): return \"<Node value=%f visits=%d",
"self.value = value self.visits = 0 self.children = {} if children is None",
"def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" % ( self.value, self.visits, len(self.children), )",
"= {} if children is None else children def __repr__(self): return \"<Node value=%f",
"value self.visits = 0 self.children = {} if children is None else children",
"import numpy as np class Node: def __init__(self, value=-np.inf, children=None): self.value = value",
"self.visits = 0 self.children = {} if children is None else children def",
"numpy as np class Node: def __init__(self, value=-np.inf, children=None): self.value = value self.visits",
"__init__(self, value=-np.inf, children=None): self.value = value self.visits = 0 self.children = {} if",
"= value self.visits = 0 self.children = {} if children is None else",
"self.children = {} if children is None else children def __repr__(self): return \"<Node",
"None else children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" % ( self.value,",
"= 0 self.children = {} if children is None else children def __repr__(self):",
"children is None else children def __repr__(self): return \"<Node value=%f visits=%d len(children)=%d>\" %",
"class Node: def __init__(self, value=-np.inf, children=None): self.value = value self.visits = 0 self.children"
] |
[
"self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\"))",
"os import unittest import shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme as",
"\"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder)",
"self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if",
"all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\")",
"import sys import os import unittest import shutil from io import StringIO sys.path.append(\".\")",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as",
"os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder",
"self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\")))",
"\"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\")))",
"gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\")))",
"os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder,",
"\"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with",
"import StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import gen_file from mock_args_container",
"= MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if",
"os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder",
"as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\"",
"Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\",",
"\"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\")))",
"os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\")",
"args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self):",
"self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args)",
"with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class",
"= \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\")",
"\"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas =",
"args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder):",
"self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh:",
"mock_args_container import MockClass from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph):",
"shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\",",
"with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\"))",
"self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self): if",
"open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder",
"\"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa",
"as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\")) if __name__",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss",
"io import StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import gen_file from",
"\"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\")))",
"from mock_args_container import MockClass from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta,",
"(not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args =",
"os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder =",
"self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if",
"def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\")",
"shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import",
"self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder)",
"me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\")",
"import os import unittest import shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme",
"fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder =",
"= Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\",",
"gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"from mock_helper import gen_file from mock_args_container import MockClass from annogesiclib.meme import MEME class",
"self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"\"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"\"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\")))",
"import MockClass from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with",
"\"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\")",
"as me from mock_helper import gen_file from mock_args_container import MockClass from annogesiclib.meme import",
"os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas",
"fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args",
"self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self):",
"mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as",
"args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def",
"tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\")",
"if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder",
"as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self):",
"\"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\")",
"(not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA",
"(not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)):",
"os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs =",
"unittest import shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme as me from",
"from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\")",
"gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"= os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not",
"self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"),",
"os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder,",
"fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder",
"\"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder)",
"(not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder =",
"= os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder",
"MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not",
"\"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if",
"fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args =",
"mock_helper import gen_file from mock_args_container import MockClass from annogesiclib.meme import MEME class Mock_func(object):",
"\"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder =",
"args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme",
"if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\",",
"ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\")) if __name__ == \"__main__\": unittest.main()",
"MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\")",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def",
"\"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\")",
"self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder",
"= MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder)",
"def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")):",
"os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock()",
"self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def",
"annogesiclib.meme as me from mock_helper import gen_file from mock_args_container import MockClass from annogesiclib.meme",
"self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta =",
"sys import os import unittest import shutil from io import StringIO sys.path.append(\".\") import",
"\"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\")) if",
"fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\")) if __name__ == \"__main__\":",
"class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with",
"\"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder)",
"\"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\")))",
"\"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\"))",
"setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)):",
"test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\",",
"import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh:",
"os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)):",
"gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join(",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"= self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self):",
"fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder, \"bbb.fa\")) if __name__ ==",
"args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder",
"Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\")",
"= self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder =",
"= self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta",
"\"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder =",
"if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder, \"tss_folder\") if (not",
"tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh:",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder,",
"if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss = self.tss_folder args.fastas = self.fa_folder",
"if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args",
"annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\", \"w\") as",
"self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder = os.path.join(self.test_folder,",
"def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\")",
"open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb AATTAATTAA\"\"\") self.meme._split_fasta_by_strain(self.fa_folder) self.assertTrue(os.path.join(self.fa_folder, \"aaa.fa\")) self.assertTrue(os.path.join(self.fa_folder,",
"(not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\")",
"= os.path.join(self.test_folder, \"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not",
"if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\",",
"self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta",
"me from mock_helper import gen_file from mock_args_container import MockClass from annogesiclib.meme import MEME",
"sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import gen_file from mock_args_container import MockClass",
"os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder,",
"self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder, \"allgenome.fa\"), \"w\") as fh: fh.write(\"\"\">aaa_aaa_aaa ATTATATATA >bbb_bbb_bbb",
"MockClass from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self, tmp_fasta, all_no_orph): with open(\"tmp/all_type.fa\",",
"class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\"",
"import shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper",
"<filename>tests/test_meme.py import sys import os import unittest import shutil from io import StringIO",
"import unittest import shutil from io import StringIO sys.path.append(\".\") import annogesiclib.meme as me",
"gen_file from mock_args_container import MockClass from annogesiclib.meme import MEME class Mock_func(object): def mock_del_repeat_fasta(self,",
"self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_internal.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder,",
"import gen_file from mock_args_container import MockClass from annogesiclib.meme import MEME class Mock_func(object): def",
"= self.gff_folder args.output_folder = self.out_folder self.meme = MEME(args) def tearDown(self): if os.path.exists(self.test_folder): shutil.rmtree(self.test_folder)",
"with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass()",
"open(\"tmp/all_type.fa\", \"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase):",
"import annogesiclib.meme as me from mock_helper import gen_file from mock_args_container import MockClass from",
"os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\") gen_file(\"tmp/secondary.fa\", \"secondary\") gen_file(\"tmp/internal.fa\", \"internal\") gen_file(\"tmp/antisense.fa\", \"antisense\") gen_file(\"tmp/orphan.fa\", \"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\")",
"from io import StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import gen_file",
"os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder) self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)):",
"= \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder, \"fasta_output\")) self.tss_folder",
"\"tss_folder\") if (not os.path.exists(self.tss_folder)): os.mkdir(self.tss_folder) self.gff_folder = os.path.join(self.test_folder, \"gff_folder\") if (not os.path.exists(self.gff_folder)): os.mkdir(self.gff_folder)",
"\"w\") as fh: fh.write(\"all\") with open(\"tmp/without_orphan.fa\", \"w\") as fh: fh.write(\"without_orphan\") class TestMEME(unittest.TestCase): def",
"TestMEME(unittest.TestCase): def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if",
"def setUp(self): self.mock_args = MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not",
"StringIO sys.path.append(\".\") import annogesiclib.meme as me from mock_helper import gen_file from mock_args_container import",
"self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_antisense.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_orphan.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_without_orphan.fa\"))) def test_split_fasta_by_strain(self): with open(os.path.join(self.fa_folder,",
"\"orphan\") self.meme._move_and_merge_fasta(self.test_folder, \"test\") self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_all_types.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_primary.fa\"))) self.assertTrue(os.path.exists(os.path.join( self.test_folder, \"test_allgenome_secondary.fa\"))) self.assertTrue(os.path.exists(os.path.join(",
"= self.tss_folder args.fastas = self.fa_folder args.gffs = self.gff_folder args.output_folder = self.out_folder self.meme =",
"MockClass() self.test_folder = \"test_folder\" self.out_folder = \"test_folder/output\" if (not os.path.exists(self.test_folder)): os.mkdir(self.test_folder) os.mkdir(self.out_folder) os.mkdir(os.path.join(self.out_folder,",
"os.path.exists(self.test_folder): shutil.rmtree(self.test_folder) def test_move_and_merge_fasta(self): me.del_repeat_fasta = Mock_func().mock_del_repeat_fasta if (not os.path.exists(\"tmp\")): os.mkdir(\"tmp\") gen_file(\"tmp/primary.fa\", \"primary\")",
"self.fa_folder = os.path.join(self.test_folder, \"fa_folder\") if (not os.path.exists(self.fa_folder)): os.mkdir(self.fa_folder) args = self.mock_args.mock() args.tsss ="
] |
[
"sqlalchemy import Column, Integer, String from .database import Base class Share(Base): __tablename__ =",
"<reponame>stakewise/bls-horcrux<filename>dispatcher/models.py from sqlalchemy import Column, Integer, String from .database import Base class Share(Base):",
"recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag",
"Base class Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key =",
"primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext =",
".database import Base class Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True)",
"String from .database import Base class Share(Base): __tablename__ = \"shares\" id = Column(Integer,",
"sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag = Column(String) nonce",
"Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext",
"__tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key =",
"from .database import Base class Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True,",
"Column, Integer, String from .database import Base class Share(Base): __tablename__ = \"shares\" id",
"class Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String)",
"import Column, Integer, String from .database import Base class Share(Base): __tablename__ = \"shares\"",
"= \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String)",
"Integer, String from .database import Base class Share(Base): __tablename__ = \"shares\" id =",
"import Base class Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key",
"enc_session_key = Column(String) ciphertext = Column(String) tag = Column(String) nonce = Column(String) signature",
"= Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag = Column(String) nonce =",
"= Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String)",
"= Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag =",
"index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext = Column(String)",
"id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key =",
"Column(String) ciphertext = Column(String) tag = Column(String) nonce = Column(String) signature = Column(String)",
"\"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key = Column(String) enc_session_key",
"Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag = Column(String) nonce = Column(String)",
"Share(Base): __tablename__ = \"shares\" id = Column(Integer, primary_key=True, index=True) recipient_rsa_public_key = Column(String) sender_rsa_public_key",
"= Column(String) ciphertext = Column(String) tag = Column(String) nonce = Column(String) signature =",
"from sqlalchemy import Column, Integer, String from .database import Base class Share(Base): __tablename__",
"Column(String) sender_rsa_public_key = Column(String) enc_session_key = Column(String) ciphertext = Column(String) tag = Column(String)"
] |
[
"is not None, 'submission matched flag to no challenge' if self.group is None",
"__future__ import annotations import time from abc import ABC, abstractmethod from typing import",
"[{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else None,",
"None, } for f in ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for",
"from . import WithGameLifecycle def minmax(x: int, a: int, b: int) -> int:",
"if ch_sub is not None else None, }] + ([] if len(ch.flags)<=1 else",
"'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub",
"board_type self.name = name @property @abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError()",
"bool): super().__init__('firstblood', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] =",
") b = [(u, u.tot_score) for u in self._game.users.list] self.board = sorted([x for",
"= {} self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch:",
"}, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or",
"self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized",
"is not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and",
"not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge':",
"x>b: return b return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name:",
"'category': ch._store.category, 'flags': [f.name for f in ch.flags], } for ch in self._game.challenges.list],",
"for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in",
"score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x return",
"self.board = sorted([x for x in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id:",
"None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}':",
"submission: Submission, in_batch: bool) -> None: if submission.matched_flag is not None: assert submission.challenge",
"(ch_sub is not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is",
"None or submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not",
"to no challenge' if self.group is None or submission.user._store.group in self.group: passed_all_flags =",
"if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)}",
"= submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if",
"__init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game =",
"u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None,",
"self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {}",
"group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game self.show_group: bool = show_group",
"summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType)",
"else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else None,",
"else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group) else None,",
"-> None: if not in_batch and submission.matched_flag is not None: if self.group is",
"MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game: Game, group:",
"Any]: return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None,",
"show_group: bool): super().__init__('score', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]]",
"b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score) in",
"and submission.matched_flag is not None: if self.group is None or submission.user._store.group in self.group:",
"= game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission]",
"None else True) and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user,",
"self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self)",
"return self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool: user, score",
"is not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not",
"and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x",
"from __future__ import annotations import time from abc import ABC, abstractmethod from typing",
"self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool: user, score =",
"= x return ( ((user._store.group in self.group) if self.group is not None else",
"self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if submission.matched_flag",
"None or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None:",
"ABC): def __init__(self, board_type: str, name: str): self.board_type = board_type self.name = name",
"str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group:",
"Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str, Any]: return { 'list': [{",
"self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if not in_batch and",
"submission.challenge is not None, 'submission matched flag to no challenge' if self.group is",
"= self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self) ->",
"'flags': [f.name for f in ch.flags], } for ch in self._game.challenges.list], 'list': [{",
"int] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str,",
"if submission.matched_flag is not None: assert submission.challenge is not None, 'submission matched flag",
"'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, } for idx,",
"ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game: Game,",
"if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and not",
"None: self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool)",
"int, b: int) -> int: if x<a: return a elif x>b: return b",
"None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None, }] + ([]",
"} for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ],",
"challenge' if self.group is None or submission.user._store.group in self.group: passed_all_flags = submission.challenge in",
"[{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else None, 'group_disp':",
"self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if submission.matched_flag is not",
"'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board",
"in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood',",
"Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from . import * ScoreBoardItemType =",
"self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board):",
"def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x return ( -score,",
"in self._game.users.list] self.board = sorted([x for x in b if is_valid(x)], key=sorter) self.uid_to_rank",
"ch_sub is not None else None, }] + ([] if len(ch.flags)<=1 else [{",
"'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000)",
"Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def",
"= {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]:",
"None: if not in_batch and submission.matched_flag is not None: if self.group is None",
"'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None",
"self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group:",
"for sub in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts,",
"time from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple,",
"[self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board = {}",
"'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions] } for",
"name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game",
"{} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] = self._summarize() @property def",
"for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], }",
"Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) ->",
"not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name,",
"= self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if submission.matched_flag is",
"'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else",
"_update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool: user, score = x return",
"ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items()",
"in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag]",
"[f.name for f in ch.flags], } for ch in self._game.challenges.list], 'list': [{ 'rank':",
"ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for ch_sub",
"None)]], } def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board = {} self._summarized",
"str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game self.show_group:",
"in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch",
"self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board = [] self._summarized =",
"def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board = {} self._summarized = self._summarize()",
"= group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str,",
"'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not",
"in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]],",
"self.flag_board[submission.matched_flag] = submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name':",
"group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any]",
"submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge]",
"name: str): self.board_type = board_type self.name = name @property @abstractmethod def summarized(self) ->",
"self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group)",
"}, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, } for",
"if ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not",
"= Tuple[User, int] from . import WithGameLifecycle def minmax(x: int, a: int, b:",
"Tuple[User, int] from . import WithGameLifecycle def minmax(x: int, a: int, b: int)",
"{ ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for",
"and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag':",
"b return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str): self.board_type",
"__init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game =",
"Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] =",
"u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000)",
"else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and self.show_group) else None,",
"None: def is_valid(x: ScoreBoardItemType) -> bool: user, score = x return ( ((user._store.group",
"[{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for",
"{} self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool)",
"10 def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name)",
"List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any] = self._summarize()",
"def _summarize(self) -> Dict[str, Any]: return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id,",
"def on_scoreboard_reset(self) -> None: self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self, submission:",
"'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board",
"{ f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, } for idx, (u,",
"no challenge' if self.group is None or submission.user._store.group in self.group: passed_all_flags = submission.challenge",
"else None, }] + ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null",
"import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from . import *",
"or '--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if",
"ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else",
"f in ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list",
"Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] = {}",
"flag to no challenge' if self.group is None or submission.user._store.group in self.group: passed_all_flags",
"on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if submission.matched_flag is not None: assert",
"int, a: int, b: int) -> int: if x<a: return a elif x>b:",
"TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from . import * ScoreBoardItemType",
"u.passed_flags.items() }, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null",
"Dict[str, Any]: return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name':",
"idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{",
"} for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--',",
"ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in ch.flags], } for ch in",
"-> None: if submission.matched_flag is not None: assert submission.challenge is not None, 'submission",
"is None or submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag",
"= game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] =",
"self.chall_board = {} self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission,",
"for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board = {}",
"None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u in self._game.users.list] self.board",
"score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch",
"is not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not",
"in ch.flags], } for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null",
"[{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions] } for u,",
". import WithGameLifecycle def minmax(x: int, a: int, b: int) -> int: if",
"-> None: def is_valid(x: ScoreBoardItemType) -> bool: user, score = x return (",
"self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class",
"not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({",
"'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None,",
"int: if x<a: return a elif x>b: return b return x class Board(WithGameLifecycle,",
"from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple, Dict,",
"([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not",
"minmax(x: int, a: int, b: int) -> int: if x<a: return a elif",
"True) and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score =",
"self.name = name @property @abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class",
"self.group is not None else True) and score>0 ) def sorter(x: ScoreBoardItemType) ->",
"= sorted([x for x in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1",
"{} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]: return",
"'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts':",
"None, 'submission matched flag to no challenge' if self.group is None or submission.user._store.group",
"submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not",
"def summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self) -> None: def is_valid(x:",
"self.group) if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not",
"is_valid(x: ScoreBoardItemType) -> bool: user, score = x return ( ((user._store.group in self.group)",
"else None, } for f in ch.flags for f_sub in [self.flag_board.get(f, None)]]), }",
"[] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any] = self._summarize() @property def",
"import WithGameLifecycle def minmax(x: int, a: int, b: int) -> int: if x<a:",
"sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions] } for u, _score in",
"def __init__(self, board_type: str, name: str): self.board_type = board_type self.name = name @property",
"self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, }",
"self._summarized def _summarize(self) -> Dict[str, Any]: return { 'list': [{ 'title': ch._store.title, 'id':",
"f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp() if",
"* ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle def minmax(x: int, a:",
"'submission matched flag to no challenge' if self.group is None or submission.user._store.group in",
"for f in ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for ch in",
"is None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u in self._game.users.list]",
"game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = []",
"sorted([x for x in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for",
"if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status':",
"or submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not in",
"name @property @abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS",
"return ( ((user._store.group in self.group) if self.group is not None else True) and",
"x return ( -score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b",
"def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS",
"ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None:",
"= [] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None:",
"} for sub in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [",
"None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp() if",
"None else None, } for f in ch.flags for f_sub in [self.flag_board.get(f, None)]]),",
"in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score':",
"in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score)",
"def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if submission.matched_flag is not None:",
"@property def summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self) -> None: def",
"ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub",
"self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) ->",
"u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in",
"self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group: Optional[List[str]],",
"u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts),",
"} def on_scoreboard_reset(self) -> None: self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self,",
"'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None, } for f in",
"is not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and",
"None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else",
"[{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub",
"'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp()",
"-> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10",
"else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': {",
"'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] =",
"self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': {",
"self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None, }]",
"if x<a: return a elif x>b: return b return x class Board(WithGameLifecycle, ABC):",
"'group_disp': u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else",
"'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None, }] + ([] if",
"summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str, Any]: return {",
"self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in",
"user, score = x return ( -score, -1 if user.last_succ_submission is None else",
"not None else None, } for f in ch.flags for f_sub in [self.flag_board.get(f,",
"_summarize(self) -> Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category':",
"Submission, in_batch: bool) -> None: if not in_batch and submission.matched_flag is not None:",
"} for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--',",
"show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission]",
"or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board()",
"import * ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle def minmax(x: int,",
"{user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]:",
"submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({",
"for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp':",
"None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group) else",
"return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str): self.board_type =",
"in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title,",
"passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname':",
"'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in ch.flags], }",
"self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self)",
"name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.chall_board:",
"= show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int]",
"'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if",
"self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self) -> None:",
"in self.group) if self.group is not None else True) and score>0 ) def",
"bool) -> None: if submission.matched_flag is not None: assert submission.challenge is not None,",
"and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None,",
"submission.matched_flag is not None: assert submission.challenge is not None, 'submission matched flag to",
"bool = show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board:",
"def minmax(x: int, a: int, b: int) -> int: if x<a: return a",
"None, }] + ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if",
"x return ( ((user._store.group in self.group) if self.group is not None else True)",
"self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if not",
"= x return ( -score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id, )",
"= [(u, u.tot_score) for u in self._game.users.list] self.board = sorted([x for x in",
"Submission, in_batch: bool) -> None: if submission.matched_flag is not None: assert submission.challenge is",
"-1 if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for",
"def summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str, Any]: return",
"or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions]",
"def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game",
"from . import * ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle def",
"show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] =",
"is not None else None, }] + ([] if len(ch.flags)<=1 else [{ 'flag_name':",
"import annotations import time from abc import ABC, abstractmethod from typing import TYPE_CHECKING,",
"is not None else None, } for f in ch.flags for f_sub in",
"if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, },",
"assert submission.challenge is not None, 'submission matched flag to no challenge' if self.group",
"raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name:",
"Any if TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User, int] from .",
"passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission",
"submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission",
"in_batch: bool) -> None: if submission.matched_flag is not None: assert submission.challenge is not",
"x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str): self.board_type = board_type",
"TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle",
"((user._store.group in self.group) if self.group is not None else True) and score>0 )",
"if (ch_sub is not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub",
"return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname':",
"group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group: bool = show_group",
"in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized =",
"= self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self) ->",
"None else None, }] + ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname':",
"'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), }",
"b: int) -> int: if x<a: return a elif x>b: return b return",
"name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game",
"MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool):",
"ScoreBoardItemType) -> bool: user, score = x return ( ((user._store.group in self.group) if",
"import time from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List,",
"None: if submission.matched_flag is not None: assert submission.challenge is not None, 'submission matched",
"in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if",
"bool) -> None: if not in_batch and submission.matched_flag is not None: if self.group",
"_summarize(self) -> Dict[str, Any]: return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags':",
"is not None: assert submission.challenge is not None, 'submission matched flag to no",
"sub in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1,",
"'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000)",
"on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str,",
"= submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge':",
"} for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self)",
"} def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board = {} self._summarized =",
"ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING:",
"self.show_group: bool = show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank:",
"Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self)",
"idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score': score,",
"-> Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str, Any]: return { 'list':",
"None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None, } for f",
"'gained_score': sub.gained_score(), } for sub in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]],",
"for f, sub in u.passed_flags.items() }, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])],",
"ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not",
"[(u, u.tot_score) for u in self._game.users.list] self.board = sorted([x for x in b",
"ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f,",
"submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board and",
"on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if not in_batch and submission.matched_flag is",
"self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize()",
"@property @abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS =",
"self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool):",
"ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp()",
"self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge,",
"user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u in self._game.users.list] self.board = sorted([x",
"import ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if",
"-> bool: user, score = x return ( ((user._store.group in self.group) if self.group",
"self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board = []",
"in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board =",
"enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id, 'title':",
"'--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission",
"Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags':",
"'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in ch.flags], } for ch",
"idx, (user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return { 'challenges':",
"-> Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category,",
"is not None else True) and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any,",
"List, Tuple, Dict, Any if TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User,",
"} for f in ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for ch",
"@abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100",
"-> Dict[str, Any]: return self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) ->",
"[self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], }",
"__init__(self, board_type: str, name: str): self.board_type = board_type self.name = name @property @abstractmethod",
"'--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions] }",
"self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group",
"group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str,",
"{} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if",
"self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood',",
"_score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self)",
"idx+1 for idx, (user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return",
"Submission] = {} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] = self._summarize()",
"-score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score)",
"f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, } for idx, (u, score)",
"def _summarize(self) -> Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title,",
"else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u in self._game.users.list] self.board =",
"-> Tuple[Any, ...]: user, score = x return ( -score, -1 if user.last_succ_submission",
"self.group is None or submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if",
"not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None",
"class FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood',",
") def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x return (",
"in self._game.challenges.list }, 'flag_pass_ts': { f'{f.challenge._store.id}_{f.idx0}': int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() },",
"submission.matched_flag is not None: if self.group is None or submission.user._store.group in self.group: self._update_board()",
"None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and self.show_group) else",
"ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is",
"game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game self.show_group: bool",
"self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, }, self.group) self._summarized =",
"elif x>b: return b return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str,",
"in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board",
"return b return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str):",
"on_scoreboard_reset(self) -> None: self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission,",
"if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None",
"(f_sub is not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is",
"name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.board:",
"'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in",
"'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub",
"], } def on_scoreboard_reset(self) -> None: self.board = [] self._summarized = self._summarize() def",
"def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name:",
"'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000)",
"not None, 'submission matched flag to no challenge' if self.group is None or",
"for u in self._game.users.list] self.board = sorted([x for x in b if is_valid(x)],",
"'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub in u.succ_submissions] } for u, _score",
"board_type: str, name: str): self.board_type = board_type self.name = name @property @abstractmethod def",
"int] from . import WithGameLifecycle def minmax(x: int, a: int, b: int) ->",
"= self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def",
"enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(),",
"else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None, }] +",
"( -score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b = [(u,",
"bool): super().__init__('score', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] =",
"passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, },",
"-> Dict[str, Any]: return { 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{",
"'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if",
"for f_sub in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for ch_sub in",
"submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title,",
"def is_valid(x: ScoreBoardItemType) -> bool: user, score = x return ( ((user._store.group in",
"submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board:",
"}, self.group) if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if",
"'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is",
"bool: user, score = x return ( ((user._store.group in self.group) if self.group is",
"self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)} def _summarize(self) ->",
"'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp()",
"and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None,",
"a: int, b: int) -> int: if x<a: return a elif x>b: return",
"abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from",
"f_sub in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch,",
"return self._summarized def _summarize(self) -> Dict[str, Any]: return { 'list': [{ 'title': ch._store.title,",
"else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None, } for",
"if submission.challenge not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch:",
"f, sub in u.passed_flags.items() }, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars':",
"not in self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type':",
"[{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in ch.flags],",
"'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge not in self.chall_board and passed_all_flags:",
"not None else None, }] + ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name,",
"u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def",
"show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]]",
"self.group) if self.group is not None else True) and score>0 ) def sorter(x:",
"not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group)",
"in_batch: bool) -> None: if not in_batch and submission.matched_flag is not None: if",
"None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group) else None, 'timestamp':",
"f_sub is not None else None, } for f in ch.flags for f_sub",
"int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list",
"{ 'list': [{ 'title': ch._store.title, 'id': ch._store.id, 'flags': [{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null",
"sub in u.passed_flags.items() }, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{",
"= group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] = {} self._summarized:",
"Any]: return self._summarized def _summarize(self) -> Dict[str, Any]: return { 'list': [{ 'title':",
"class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game:",
"if not in_batch and submission.matched_flag is not None: if self.group is None or",
"[] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if",
"Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game self.show_group: bool =",
"self.chall_board and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name':",
"for idx, (user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return {",
"None: assert submission.challenge is not None, 'submission matched flag to no challenge' if",
"if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u",
"-> None: self.chall_board = {} self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self,",
"str, name: str): self.board_type = board_type self.name = name @property @abstractmethod def summarized(self)",
"self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self,",
"abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any",
"from typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from .",
"in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, }, self.group) self._summarized",
"if self.group is None or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def",
"None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and self.show_group) else None, 'timestamp':",
"ch_sub.user._store.group_disp() if (ch_sub is not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if",
"not None: assert submission.challenge is not None, 'submission matched flag to no challenge'",
"self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None, }",
"on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board = {} self._summarized = self._summarize() def",
"int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else None, }] + ([] if len(ch.flags)<=1",
"100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group:",
"bool = show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int,",
"def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool: user, score = x",
"class Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str): self.board_type = board_type self.name",
"if (f_sub is not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if f_sub",
"None: self.chall_board = {} self.flag_board = {} self._summarized = self._summarize() def on_scoreboard_update(self, submission:",
"user, score = x return ( ((user._store.group in self.group) if self.group is not",
"Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group: bool = show_group self.group:",
"self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board =",
"Dict, Any if TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User, int] from",
"...]: user, score = x return ( -score, -1 if user.last_succ_submission is None",
"game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] =",
"a elif x>b: return b return x class Board(WithGameLifecycle, ABC): def __init__(self, board_type:",
"is not None: if self.group is None or submission.user._store.group in self.group: self._update_board() self._summarized",
"x in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user,",
"if f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not",
"Tuple[Any, ...]: user, score = x return ( -score, -1 if user.last_succ_submission is",
"int(sub._store.timestamp_ms/1000) for f, sub in u.passed_flags.items() }, } for idx, (u, score) in",
"b = [(u, u.tot_score) for u in self._game.users.list] self.board = sorted([x for x",
"in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) ->",
"u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list }, 'flag_pass_ts':",
"[{ 'flag_name': None, 'nickname': ch_sub.user._store.profile.nickname_or_null if ch_sub is not None else None, 'group_disp':",
"None: if self.group is None or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize()",
"'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, 'flag': submission.matched_flag.name, }, self.group) if submission.challenge",
"u in self._game.users.list] self.board = sorted([x for x in b if is_valid(x)], key=sorter)",
"str): self.board_type = board_type self.name = name @property @abstractmethod def summarized(self) -> Dict[str,",
"ch.flags], } for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or",
"self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) ->",
"None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None else",
"}] + ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub",
"(u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms':",
"-> None: self.board = [] self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch:",
"return ( -score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id, ) b =",
"for f in ch.flags], } for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1,",
"self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group self.board: List[ScoreBoardItemType]",
"= board_type self.name = name @property @abstractmethod def summarized(self) -> Dict[str, Any]: raise",
"score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms,",
"submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) -> None: self._update_board() self._summarized",
"+ ([] if len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is",
"self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any]",
"game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group: bool",
"(user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return { 'challenges': [{",
"in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return { 'challenges': [{ 'id': ch._store.id,",
"score = x return ( ((user._store.group in self.group) if self.group is not None",
"Submission] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) -> Dict[str,",
"submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname':",
"= {} self.flag_board: Dict[Flag, Submission] = {} self._summarized: Dict[str, Any] = self._summarize() @property",
"x<a: return a elif x>b: return b return x class Board(WithGameLifecycle, ABC): def",
"WithGameLifecycle def minmax(x: int, a: int, b: int) -> int: if x<a: return",
"NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str,",
"if self.group is None or submission.user._store.group in self.group: passed_all_flags = submission.challenge in submission.user.passed_challs",
"u.tot_score) for u in self._game.users.list] self.board = sorted([x for x in b if",
"self.group is None or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self)",
"user.last_succ_submission is None else user.last_succ_submission._store.id, ) b = [(u, u.tot_score) for u in",
"annotations import time from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional,",
"Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def",
"f in ch.flags], } for ch in self._game.challenges.list], 'list': [{ 'rank': idx+1, 'nickname':",
"self.board_type = board_type self.name = name @property @abstractmethod def summarized(self) -> Dict[str, Any]:",
"( ((user._store.group in self.group) if self.group is not None else True) and score>0",
"self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag, Submission] =",
"'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for",
"'nickname': u._store.profile.nickname_or_null or '--', 'submissions': [{ 'timestamp_ms': sub._store.timestamp_ms, 'gained_score': sub.gained_score(), } for sub",
"if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in self._game.challenges.list },",
"'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, }, self.group) self._summarized = self._summarize()",
"summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS =",
"else True) and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score",
"FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name)",
"in u.passed_flags.items() }, } for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname':",
"in ch.flags for f_sub in [self.flag_board.get(f, None)]]), } for ch in self._game.challenges.list for",
"minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board = [] self._summarized",
"if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null,",
"self.show_group: bool = show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {}",
"not None: if self.group is None or submission.user._store.group in self.group: self._update_board() self._summarized =",
"len(ch.flags)<=1 else [{ 'flag_name': f.name, 'nickname': f_sub.user._store.profile.nickname_or_null if f_sub is not None else",
"super().__init__('firstblood', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group",
"submission: Submission, in_batch: bool) -> None: if not in_batch and submission.matched_flag is not",
"Optional[List[str]] = group self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {} self._summarized:",
"[ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board =",
"and passed_all_flags: self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name,",
"= name @property @abstractmethod def summarized(self) -> Dict[str, Any]: raise NotImplementedError() class ScoreBoard(Board):",
"self._game.users.list] self.board = sorted([x for x in b if is_valid(x)], key=sorter) self.uid_to_rank =",
"not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None and self.show_group)",
"is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)} def",
"self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1, self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None:",
"self.chall_board[submission.challenge] = submission if not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null,",
". import * ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle def minmax(x:",
"'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u) for ch in",
"submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and not passed_all_flags:",
"ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f in ch.flags], } for",
"in_batch and submission.matched_flag is not None: if self.group is None or submission.user._store.group in",
"None)]]), } for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def",
"in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type':",
"ch_sub is not None else None, 'group_disp': ch_sub.user._store.group_disp() if (ch_sub is not None",
"_score) in enumerate(self.board)} def _summarize(self) -> Dict[str, Any]: return { 'challenges': [{ 'id':",
"= submission if not in_batch and not passed_all_flags: self._game.worker.emit_local_message({ 'type': 'flag_first_blood', 'board_name': self.name,",
"def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if not in_batch and submission.matched_flag",
"Dict[int, int] = {} self._summarized: Dict[str, Any] = self._summarize() @property def summarized(self) ->",
"if f_sub is not None else None, } for f in ch.flags for",
"= self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group:",
"self.group: passed_all_flags = submission.challenge in submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] =",
"= {} self._summarized = self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None:",
"Optional[List[str]], show_group: bool): super().__init__('score', name) self._game = game self.show_group: bool = show_group self.group:",
"not in_batch and submission.matched_flag is not None: if self.group is None or submission.user._store.group",
"None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id: ch.user_status(u)",
"= 100 MAX_TOPSTAR_USERS = 10 def __init__(self, name: str, game: Game, group: Optional[List[str]],",
"ch._store.category, 'flags': [f.name for f in ch.flags], } for ch in self._game.challenges.list], 'list':",
"submission.user.passed_challs if submission.matched_flag not in self.flag_board: self.flag_board[submission.matched_flag] = submission if not in_batch and",
"typing import TYPE_CHECKING, Optional, List, Tuple, Dict, Any if TYPE_CHECKING: from . import",
"Any]: return self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool: user,",
"return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for",
"else None, 'score': score, 'last_succ_submission_ts': int(u.last_succ_submission._store.timestamp_ms/1000) if u.last_succ_submission else None, 'challenge_status': { ch._store.id:",
"return a elif x>b: return b return x class Board(WithGameLifecycle, ABC): def __init__(self,",
"sub.gained_score(), } for sub in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range':",
"= {user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)} def _summarize(self) -> Dict[str,",
"for ch in self._game.challenges.list for ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) ->",
"= show_group self.group: Optional[List[str]] = group self.chall_board: Dict[Challenge, Submission] = {} self.flag_board: Dict[Flag,",
"ch_sub in [self.chall_board.get(ch, None)]], } def on_scoreboard_reset(self) -> None: self.chall_board = {} self.flag_board",
"= 10 def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score',",
"f_sub.user._store.group_disp() if (f_sub is not None and self.show_group) else None, 'timestamp': int(f_sub._store.timestamp_ms/1000) if",
"'rank': idx+1, 'nickname': u._store.profile.nickname_or_null or '--', 'group_disp': u._store.group_disp() if self.show_group else None, 'score':",
"if TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User, int] from . import",
"def __init__(self, name: str, game: Game, group: Optional[List[str]], show_group: bool): super().__init__('score', name) self._game",
"in u.succ_submissions] } for u, _score in self.board[:self.MAX_TOPSTAR_USERS]], 'time_range': [ self._game.trigger.board_begin_ts, minmax(int(time.time())+1, self._game.trigger.board_begin_ts+1,",
"Any]: return { 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name",
"{ 'challenges': [{ 'id': ch._store.id, 'title': ch._store.title, 'category': ch._store.category, 'flags': [f.name for f",
"not in_batch: self._game.worker.emit_local_message({ 'type': 'challenge_first_blood', 'board_name': self.name, 'nickname': submission.user._store.profile.nickname_or_null, 'challenge': submission.challenge._store.title, }, self.group)",
"Board(WithGameLifecycle, ABC): def __init__(self, board_type: str, name: str): self.board_type = board_type self.name =",
"for x in b if is_valid(x)], key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx,",
"score = x return ( -score, -1 if user.last_succ_submission is None else user.last_succ_submission._store.id,",
"Dict[str, Any]: return self._summarized def _update_board(self) -> None: def is_valid(x: ScoreBoardItemType) -> bool:",
"= self._summarize() def on_scoreboard_update(self, submission: Submission, in_batch: bool) -> None: if not in_batch",
"Any] = self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _update_board(self)",
"Tuple, Dict, Any if TYPE_CHECKING: from . import * ScoreBoardItemType = Tuple[User, int]",
"self._game.trigger.board_end_ts), ], } def on_scoreboard_reset(self) -> None: self.board = [] self._summarized = self._summarize()",
"super().__init__('score', name) self._game = game self.show_group: bool = show_group self.group: Optional[List[str]] = group",
"self._summarize() @property def summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str,",
"-> int: if x<a: return a elif x>b: return b return x class",
"-> None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game:",
"Game, group: Optional[List[str]], show_group: bool): super().__init__('firstblood', name) self._game = game self.show_group: bool =",
"is None or submission.user._store.group in self.group: self._update_board() self._summarized = self._summarize() def on_scoreboard_batch_update_done(self) ->",
"int) -> int: if x<a: return a elif x>b: return b return x",
"key=sorter) self.uid_to_rank = {user._store.id: idx+1 for idx, (user, _score) in enumerate(self.board)} def _summarize(self)",
"= [] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any] = self._summarize() @property",
"Any]: raise NotImplementedError() class ScoreBoard(Board): MAX_DISPLAY_USERS = 100 MAX_TOPSTAR_USERS = 10 def __init__(self,",
"f_sub.user._store.profile.nickname_or_null if f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is",
"for idx, (u, score) in enumerate(self.board[:self.MAX_DISPLAY_USERS])], 'topstars': [{ 'nickname': u._store.profile.nickname_or_null or '--', 'submissions':",
"not None else True) and score>0 ) def sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]:",
"self.board: List[ScoreBoardItemType] = [] self.uid_to_rank: Dict[int, int] = {} self._summarized: Dict[str, Any] =",
"matched flag to no challenge' if self.group is None or submission.user._store.group in self.group:",
"f_sub is not None else None, 'group_disp': f_sub.user._store.group_disp() if (f_sub is not None",
"sorter(x: ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x return ( -score, -1",
"ScoreBoardItemType) -> Tuple[Any, ...]: user, score = x return ( -score, -1 if",
"None: self._update_board() self._summarized = self._summarize() class FirstBloodBoard(Board): def __init__(self, name: str, game: Game,",
"int(f_sub._store.timestamp_ms/1000) if f_sub is not None else None, } for f in ch.flags",
"not None and self.show_group) else None, 'timestamp': int(ch_sub._store.timestamp_ms/1000) if ch_sub is not None",
"if self.group is not None else True) and score>0 ) def sorter(x: ScoreBoardItemType)",
"ScoreBoardItemType = Tuple[User, int] from . import WithGameLifecycle def minmax(x: int, a: int,",
"@property def summarized(self) -> Dict[str, Any]: return self._summarized def _summarize(self) -> Dict[str, Any]:"
] |
[
"print('Acquired lock: %s' % self.fddr()) except: if self.debug: lock = self._readlock() print('Existing lock",
"lock info''' lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) ==",
"* from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self if",
"lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid =",
"this to get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ +",
"[ self.path, '', 0 ] return lock def ownlock(self): '''Check if we own",
"SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr()) except: print(\" Error",
"except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock:",
"successful, False otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired",
"lock detected: %s' % self.pddr(lock)) return False return self def release(self): '''Release lock,",
"# set this to get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \"",
"%s' % self.fddr()) return self def _readlock(self): '''Internal method to read lock info'''",
"Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr()) except: print(\" Error (%s): unable",
"self.host) fddr = lambda self: '<%s %s>' % (self.path, self.addr()) pddr = lambda",
"Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '',",
"__init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path = path self.debug = debug",
"Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self if successful, False",
"to handle creating and removing database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception):",
"'%d@%s' % (self.pid, self.host) fddr = lambda self: '<%s %s>' % (self.path, self.addr())",
"SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr()) except: if self.debug:",
"method to read lock info''' lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall()",
"def acquire(self): '''Acquire a lock, returning self if successful, False otherwise''' try: #",
"pddr = lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None):",
"try: # Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' %",
"self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid()",
"# custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables for",
"elif len(results) > 1: print(' WARNING -- did not find unique result! (n=%d)'%(len(results)))",
"self.pddr(lock)) def __del__(self): '''Magic method to clean up lock when program exits''' self.release()",
"locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables",
"unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return",
"_readlock(self): '''Internal method to read lock info''' lock = {} try: Cursor.execute(self.listSql) results",
"self.path = path self.debug = debug # set this to get status messages",
"the lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method",
"self def release(self): '''Release lock, returning self''' if self.ownlock(): try: # Execute the",
"lambda self: '<%s %s>' % (self.path, self.addr()) pddr = lambda self, lock: '<%s",
"lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return self def _readlock(self):",
"= [ self.path, '', 0 ] else: for row in results: lock['path'], lock['host'],",
"False otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock:",
"def _readlock(self): '''Internal method to read lock info''' lock = {} try: Cursor.execute(self.listSql)",
"> 1: print(' WARNING -- did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'],",
"= [ self.path, '', 0 ] return lock def ownlock(self): '''Check if we",
"we own the lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self):",
"MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db",
"DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr = lambda self: '%d@%s' %",
"= {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'],",
"'', 0 ] return lock def ownlock(self): '''Check if we own the lock'''",
"== self.pddr(lock)) def __del__(self): '''Magic method to clean up lock when program exits'''",
"detected: %s' % self.pddr(lock)) return False return self def release(self): '''Release lock, returning",
"self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete",
"DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr = lambda",
"socket.gethostname() self.path = path self.debug = debug # set this to get status",
"addr = lambda self: '%d@%s' % (self.pid, self.host) fddr = lambda self: '<%s",
"did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '',",
"lock['host'], lock['pid'] = row except: print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'],",
"where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire",
"list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] return lock",
"+ \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select",
"Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self):",
"'<%s %s>' % (self.path, self.addr()) pddr = lambda self, lock: '<%s %s@%s>' %\\",
"\"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\")",
"removing database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass",
"(self.pid, self.host) fddr = lambda self: '<%s %s>' % (self.path, self.addr()) pddr =",
"'<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host =",
"LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self if successful, False otherwise''' try:",
"return self def release(self): '''Release lock, returning self''' if self.ownlock(): try: # Execute",
"self.fddr()) except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing",
"(self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return self def _readlock(self): '''Internal method",
"the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr()) except: if",
"0 ] elif len(results) > 1: print(' WARNING -- did not find unique",
"lock = self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to clean",
"else: for row in results: lock['path'], lock['host'], lock['pid'] = row except: print(\" Error",
"= \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object):",
"self.path, '', 0 ] return lock def ownlock(self): '''Check if we own the",
"'', 0 ] else: for row in results: lock['path'], lock['host'], lock['pid'] = row",
"lock['host'], lock['pid'] = [ self.path, '', 0 ] return lock def ownlock(self): '''Check",
"print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to",
"lock = self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return False return self",
"print('Existing lock detected: %s' % self.pddr(lock)) return False return self def release(self): '''Release",
"= lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid",
"= \"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning",
"= debug # set this to get status messages self.acquireSql = \"insert into",
"print(' WARNING -- did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] =",
"'''Internal method to read lock info''' lock = {} try: Cursor.execute(self.listSql) results =",
"print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s'",
"len(results) == 0: lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] elif",
"lock['pid'] = [ self.path, '', 0 ] elif len(results) > 1: print(' WARNING",
"row except: print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] =",
"print('Released lock: %s' % self.fddr()) except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql))",
"'Error releasing lock: %s' % self.fddr()) return self def _readlock(self): '''Internal method to",
"callables for formatting addr = lambda self: '%d@%s' % (self.pid, self.host) fddr =",
"own the lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic",
"lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] return lock def ownlock(self):",
"# dblock.py import os import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not",
"lock, returning self if successful, False otherwise''' try: # Execute the SQL command",
"Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr()) except:",
"Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' %",
"lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to",
"fddr = lambda self: '<%s %s>' % (self.path, self.addr()) pddr = lambda self,",
"custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting",
"lock['pid'] = [ self.path, '', 0 ] else: for row in results: lock['path'],",
"= lambda self: '<%s %s>' % (self.path, self.addr()) pddr = lambda self, lock:",
"self.addr()) pddr = lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def",
"from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self if successful,",
"results = Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid'] = [ self.path,",
"except: if self.debug: lock = self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return",
"'''Class to handle creating and removing database based locks''' # custom exceptions class",
"lock['host'], lock['pid'] = [ self.path, '', 0 ] elif len(results) > 1: print('",
"-- did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path,",
"for row in results: lock['path'], lock['host'], lock['pid'] = row except: print(\" Error (%s):",
"\"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class",
"'''Check if we own the lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock))",
"LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a",
"'''Acquire a lock, returning self if successful, False otherwise''' try: # Execute the",
"Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr()) except:",
"os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor()",
"self.host = socket.gethostname() self.path = path self.debug = debug # set this to",
"\"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks",
"not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor =",
"import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN",
"def release(self): '''Release lock, returning self''' if self.ownlock(): try: # Execute the SQL",
"%s' % self.pddr(lock)) return False return self def release(self): '''Release lock, returning self'''",
"result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] else: for",
"if self.debug: lock = self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return False",
"and removing database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception):",
"self if successful, False otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql) if",
"<gh_stars>0 # dblock.py import os import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if",
"pass class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr = lambda self:",
"pass # convenience callables for formatting addr = lambda self: '%d@%s' % (self.pid,",
"debug # set this to get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid)",
"if self.debug: print('Acquired lock: %s' % self.fddr()) except: if self.debug: lock = self._readlock()",
"[ self.path, '', 0 ] elif len(results) > 1: print(' WARNING -- did",
"1: print(' WARNING -- did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid']",
"False return self def release(self): '''Release lock, returning self''' if self.ownlock(): try: #",
"release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return self def",
"lock def ownlock(self): '''Check if we own the lock''' lock = self._readlock() return",
"except: print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [",
"creating and removing database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class",
"release(self): '''Release lock, returning self''' if self.ownlock(): try: # Execute the SQL command",
"# Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr())",
"lock['pid'] = row except: print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'],",
"acquire(self): '''Acquire a lock, returning self if successful, False otherwise''' try: # Execute",
"[ self.path, '', 0 ] else: for row in results: lock['path'], lock['host'], lock['pid']",
"convenience callables for formatting addr = lambda self: '%d@%s' % (self.pid, self.host) fddr",
"(%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr())",
"0 ] return lock def ownlock(self): '''Check if we own the lock''' lock",
"= self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return False return self def",
"] return lock def ownlock(self): '''Check if we own the lock''' lock =",
"import os import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF",
"if we own the lock''' lock = self._readlock() return (self.fddr() == self.pddr(lock)) def",
"return lock def ownlock(self): '''Check if we own the lock''' lock = self._readlock()",
"unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ]",
"lock: %s' % self.fddr()) return self def _readlock(self): '''Internal method to read lock",
"Db.cursor() class dblock(object): '''Class to handle creating and removing database based locks''' #",
"(self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path =",
"locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] return lock def",
"self.pid = os.getpid() self.host = socket.gethostname() self.path = path self.debug = debug #",
"self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks",
"% self.fddr()) return self def _readlock(self): '''Internal method to read lock info''' lock",
"{} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid']",
"Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0",
"(%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0",
"MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to handle creating and removing database",
"dblock(object): '''Class to handle creating and removing database based locks''' # custom exceptions",
"self.pddr(lock)) return False return self def release(self): '''Release lock, returning self''' if self.ownlock():",
"if self.debug: print('Released lock: %s' % self.fddr()) except: print(\" Error (%s): unable to",
"= row except: print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid']",
"lock: %s' % self.fddr()) except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise",
"exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr",
"lambda self: '%d@%s' % (self.pid, self.host) fddr = lambda self: '<%s %s>' %",
"= \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from",
"otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s'",
"lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] elif len(results) > 1:",
"Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr()) except: if self.debug: lock =",
"self def _readlock(self): '''Internal method to read lock info''' lock = {} try:",
"set this to get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\",
"% self.pddr(lock)) return False return self def release(self): '''Release lock, returning self''' if",
"if successful, False otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql) if self.debug:",
"the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr()) except: print(\"",
"get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid)",
"into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where",
"\"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path)",
"self.debug: print('Acquired lock: %s' % self.fddr()) except: if self.debug: lock = self._readlock() print('Existing",
"= \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db =",
"releasing lock: %s' % self.fddr()) return self def _readlock(self): '''Internal method to read",
"formatting addr = lambda self: '%d@%s' % (self.pid, self.host) fddr = lambda self:",
"try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid'] =",
"\" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql",
"'', 0 ] elif len(results) > 1: print(' WARNING -- did not find",
"dblock.py import os import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF):",
"= lambda self: '%d@%s' % (self.pid, self.host) fddr = lambda self: '<%s %s>'",
"read lock info''' lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results)",
"lock['host'], lock['pid'] = [ self.path, '', 0 ] else: for row in results:",
"MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\")",
"# convenience callables for formatting addr = lambda self: '%d@%s' % (self.pid, self.host)",
"status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql",
"\" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select *",
"(self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to clean up lock when program",
"% (self.pid, self.host) fddr = lambda self: '<%s %s>' % (self.path, self.addr()) pddr",
"path self.debug = debug # set this to get status messages self.acquireSql =",
"find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ]",
"'''Release lock, returning self''' if self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql)",
"self.fddr()) return self def _readlock(self): '''Internal method to read lock info''' lock =",
"WARNING -- did not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [",
"lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] else: for row in",
"from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path) def",
"row in results: lock['path'], lock['host'], lock['pid'] = row except: print(\" Error (%s): unable",
"%\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path",
"lock['path'], lock['host'], lock['pid'] = row except: print(\" Error (%s): unable to list locks.\"%(self.listSql))",
"to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] return",
"self''' if self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released",
"== 0: lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] elif len(results)",
"for formatting addr = lambda self: '%d@%s' % (self.pid, self.host) fddr = lambda",
"return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to clean up lock when",
"class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr =",
"in results: lock['path'], lock['host'], lock['pid'] = row except: print(\" Error (%s): unable to",
"DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to handle creating",
"Cursor = Db.cursor() class dblock(object): '''Class to handle creating and removing database based",
"Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path)",
"self: '%d@%s' % (self.pid, self.host) fddr = lambda self: '<%s %s>' % (self.path,",
"unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] else:",
"%s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname()",
"class DatabaseLockReleaseError(Exception): pass # convenience callables for formatting addr = lambda self: '%d@%s'",
"self.path, '', 0 ] else: for row in results: lock['path'], lock['host'], lock['pid'] =",
"% self.fddr()) except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error",
"not find unique result! (n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0",
"= \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from Locks where",
"where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self if successful, False otherwise'''",
"if len(results) == 0: lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ]",
"self.listSql = \"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock,",
"self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return False return self def release(self):",
"(self.path, self.addr()) pddr = lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host'])",
"] else: for row in results: lock['path'], lock['host'], lock['pid'] = row except: print(\"",
"len(results) > 1: print(' WARNING -- did not find unique result! (n=%d)'%(len(results))) lock['path'],",
"lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path = path",
"% (self.path, self.addr()) pddr = lambda self, lock: '<%s %s@%s>' %\\ (self.path, lock['pid'],",
"database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass #",
"def ownlock(self): '''Check if we own the lock''' lock = self._readlock() return (self.fddr()",
"= self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to clean up",
"MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class",
"# Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr())",
"\"select * from Locks where LockPath='%s';\"%(self.path) def acquire(self): '''Acquire a lock, returning self",
"self.fddr()) except: if self.debug: lock = self._readlock() print('Existing lock detected: %s' % self.pddr(lock))",
"= socket.gethostname() self.path = path self.debug = debug # set this to get",
"lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path = path self.debug",
"\\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql =",
"lock, returning self''' if self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql) if",
"returning self''' if self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql) if self.debug:",
"Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid'] = [",
"ownlock(self): '''Check if we own the lock''' lock = self._readlock() return (self.fddr() ==",
"lock: '<%s %s@%s>' %\\ (self.path, lock['pid'], lock['host']) def __init__(self,path,debug=None): self.pid = os.getpid() self.host",
"def __init__(self,path,debug=None): self.pid = os.getpid() self.host = socket.gethostname() self.path = path self.debug =",
"self.path, '', 0 ] elif len(results) > 1: print(' WARNING -- did not",
"to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return self",
"0: lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] elif len(results) >",
"= [ self.path, '', 0 ] elif len(results) > 1: print(' WARNING --",
"command Cursor.execute(self.acquireSql) if self.debug: print('Acquired lock: %s' % self.fddr()) except: if self.debug: lock",
"= os.getpid() self.host = socket.gethostname() self.path = path self.debug = debug # set",
"%s' % self.fddr()) except: if self.debug: lock = self._readlock() print('Existing lock detected: %s'",
"if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\" OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor",
"based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass class DatabaseLockReleaseError(Exception): pass # convenience",
"try: # Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' %",
"a lock, returning self if successful, False otherwise''' try: # Execute the SQL",
"print(\" Error (%s): unable to list locks.\"%(self.listSql)) lock['path'], lock['host'], lock['pid'] = [ self.path,",
"= Cursor.fetchall() if len(results) == 0: lock['path'], lock['host'], lock['pid'] = [ self.path, '',",
"self._readlock() return (self.fddr() == self.pddr(lock)) def __del__(self): '''Magic method to clean up lock",
"results: lock['path'], lock['host'], lock['pid'] = row except: print(\" Error (%s): unable to list",
"= MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to handle creating and removing",
"os import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF =",
"0 ] else: for row in results: lock['path'], lock['host'], lock['pid'] = row except:",
"if self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock:",
"%s>' % (self.path, self.addr()) pddr = lambda self, lock: '<%s %s@%s>' %\\ (self.path,",
"return self def _readlock(self): '''Internal method to read lock info''' lock = {}",
"returning self if successful, False otherwise''' try: # Execute the SQL command Cursor.execute(self.acquireSql)",
"info''' lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0:",
"socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\" print(\"",
"command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s' % self.fddr()) except: print(\" Error (%s):",
"Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to handle creating and",
"%s' % self.fddr()) except: print(\" Error (%s): unable to release lock.\"%(self.releaseSql)) raise (self.DatabaseLockReleaseError,",
"lock: %s' % self.fddr()) except: if self.debug: lock = self._readlock() print('Existing lock detected:",
"(n=%d)'%(len(results))) lock['path'], lock['host'], lock['pid'] = [ self.path, '', 0 ] else: for row",
"class dblock(object): '''Class to handle creating and removing database based locks''' # custom",
"lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if len(results) == 0: lock['path'],",
"handle creating and removing database based locks''' # custom exceptions class DatabaseLockAcquisitionError(Exception): pass",
"% self.fddr()) except: if self.debug: lock = self._readlock() print('Existing lock detected: %s' %",
"= path self.debug = debug # set this to get status messages self.acquireSql",
"values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql = \"delete from Locks where LockPath='%s'\"%(self.path) self.listSql = \"select * from",
"raise (self.DatabaseLockReleaseError, 'Error releasing lock: %s' % self.fddr()) return self def _readlock(self): '''Internal",
"to read lock info''' lock = {} try: Cursor.execute(self.listSql) results = Cursor.fetchall() if",
"OPEN DB.\") Db = MySQLdb.connect(read_default_file=\"%s\"%(MY_CNF),read_default_group=\"mysql\",db=\"Fibs\") Cursor = Db.cursor() class dblock(object): '''Class to handle",
"self.debug = debug # set this to get status messages self.acquireSql = \"insert",
"self.debug: print('Released lock: %s' % self.fddr()) except: print(\" Error (%s): unable to release",
"self.ownlock(): try: # Execute the SQL command Cursor.execute(self.releaseSql) if self.debug: print('Released lock: %s'",
"self.debug: lock = self._readlock() print('Existing lock detected: %s' % self.pddr(lock)) return False return",
"] elif len(results) > 1: print(' WARNING -- did not find unique result!",
"= Db.cursor() class dblock(object): '''Class to handle creating and removing database based locks'''",
"import socket import MySQLdb MY_CNF = \"%s/.mysql/my.cnf\"%(os.getenv('HOME')) if not os.path.exists(MY_CNF): MY_CNF = \"/etc//my.cnf\"",
"self: '<%s %s>' % (self.path, self.addr()) pddr = lambda self, lock: '<%s %s@%s>'",
"to get status messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \"",
"lock['pid'] = [ self.path, '', 0 ] return lock def ownlock(self): '''Check if",
"messages self.acquireSql = \"insert into Locks(LockPath,LockHost,LockPid) \" \\ + \" values('%s','%s',%d);\"%(self.path,self.host,self.pid) self.releaseSql =",
"return False return self def release(self): '''Release lock, returning self''' if self.ownlock(): try:",
"os.getpid() self.host = socket.gethostname() self.path = path self.debug = debug # set this"
] |
[] |
[
">>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only way to get the",
"not (level is None): cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version)",
"find semver at %s\" % bin_path) return bin_path # get_semver_path() def semver_inc(version, level",
"'minor', preid = 'dev') '1.1.0' The only way to get the `preid` appended",
"def qb_read_version(file_path): '''Read a QB::Package::Version from a file. ''' with open(file_path, 'r') as",
"def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, }",
"version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def qb_version_parse(version_string): '''Parse version",
"[ get_semver_path(), '--increment', ] if not (level is None): cmd.append(level) if not (preid",
"(level is None): cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out",
"probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>>",
"testing - call camel_case on first cli arg and print result if __name__",
"= version['prerelease'][0] # depreciated name for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\"",
"'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule # testing",
"'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ] if not (level is",
"= 'dev') '1.1.0' The only way to get the `preid` appended is to",
"get_semver_path(), '--increment', ] if not (level is None): cmd.append(level) if not (preid is",
"= len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] ==",
"the version at level, with optional preid for pre- levels. runs semver --increment",
"= type import subprocess import os import json import sys from ansible.errors import",
"# semver_inc() def semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))'''",
"call camel_case on first cli arg and print result if __name__ == '__main__':",
"bin_path) return bin_path # get_semver_path() def semver_inc(version, level = None, preid = None):",
"you probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1'",
"def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path):",
"'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The",
"json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) > 0 and",
"- call camel_case on first cli arg and print result if __name__ ==",
"] if not (level is None): cmd.append(level) if not (preid is None): cmd.append('--preid')",
"os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver at",
"= 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only way",
") version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' ) if",
"= None): '''increment the version at level, with optional preid for pre- levels.",
"preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only",
"def semver_inc(version, level = None, preid = None): '''increment the version at level,",
"level, with optional preid for pre- levels. runs semver --increment <level> [--preid <preid>]",
"# depreciated name for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version",
"cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse",
"out = subprocess.check_output( cmd, cwd = qb.ROOT ) version = json.loads(out) version['is_release'] =",
"with open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters",
"--increment <level> [--preid <preid>] <version> This does **not** do what you probably want...",
"'rc' ) if version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0] # depreciated",
"== 'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc'",
"'r') as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters ''' def",
"'--eval', stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT ) version = json.loads(out)",
"0 and version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0 and",
"cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. '''",
"out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null,",
"way to get the `preid` appended is to increment the prerelease: >>> semver_inc('1.0.0',",
"sys from ansible.errors import AnsibleError import qb from qb.ipc.rpc import client as rpc_client",
">>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment',",
"semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only way to get the `preid`",
"is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' '''",
"if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip()",
"semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def",
"as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters ''' def filters(self):",
"= 'release' else: version['level'] = version['prerelease'][0] # depreciated name for level version['type'] =",
"= version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def qb_version_parse(version_string):",
"from ansible.errors import AnsibleError import qb from qb.ipc.rpc import client as rpc_client def",
"what you probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev')",
"preid = 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ] if not",
"stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd = ['node', '--eval',",
"= None, preid = None): '''increment the version at level, with optional preid",
">>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev')",
"len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] = 'release'",
"subprocess import os import json import sys from ansible.errors import AnsibleError import qb",
"import subprocess import os import json import sys from ansible.errors import AnsibleError import",
"type import subprocess import os import json import sys from ansible.errors import AnsibleError",
"cmd = [ get_semver_path(), '--increment', ] if not (level is None): cmd.append(level) if",
"''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a file.",
"pre- levels. runs semver --increment <level> [--preid <preid>] <version> This does **not** do",
"os import json import sys from ansible.errors import AnsibleError import qb from qb.ipc.rpc",
"qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule # testing - call camel_case",
"(absolute_import, division, print_function) __metaclass__ = type import subprocess import os import json import",
"semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule #",
"version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0]",
"> 0 and version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0",
"cmd, cwd = qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0",
"filters() # FilterModule # testing - call camel_case on first cli arg and",
"# testing - call camel_case on first cli arg and print result if",
"from __future__ import (absolute_import, division, print_function) __metaclass__ = type import subprocess import os",
"version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0]",
"'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" %",
"if not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" % bin_path) return bin_path",
"rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path):",
"'''Read a QB::Package::Version from a file. ''' with open(file_path, 'r') as file: return",
"len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev'",
"'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" % bin_path)",
"is None): cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out =",
"'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only way to",
"cmd = ['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT )",
"version at level, with optional preid for pre- levels. runs semver --increment <level>",
"else: version['level'] = version['prerelease'][0] # depreciated name for level version['type'] = version['level'] version['release']",
"ansible.errors import AnsibleError import qb from qb.ipc.rpc import client as rpc_client def get_semver_path():",
"= subprocess.check_output( cmd, cwd = qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease'])",
"is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def",
"file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters ''' def filters(self): return",
"2))''' % json.dumps(version) ) cmd = ['node', '--eval', stmt] out = subprocess.check_output( cmd,",
"return bin_path # get_semver_path() def semver_inc(version, level = None, preid = None): '''increment",
"import AnsibleError import qb from qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path",
"preid = 'dev') '1.1.0' The only way to get the `preid` appended is",
"% json.dumps(version) ) cmd = ['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd",
"version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' ) version['is_rc'] =",
"file. ''' with open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version",
"runs semver --increment <level> [--preid <preid>] <version> This does **not** do what you",
"= [ get_semver_path(), '--increment', ] if not (level is None): cmd.append(level) if not",
"'dev') '1.1.0' The only way to get the `preid` appended is to increment",
"% bin_path) return bin_path # get_semver_path() def semver_inc(version, level = None, preid =",
"return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s),",
"cwd = qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev']",
"optional preid for pre- levels. runs semver --increment <level> [--preid <preid>] <version> This",
"'1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ] if not (level is None):",
"The only way to get the `preid` appended is to increment the prerelease:",
"(preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc()",
"qb from qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules',",
"semver at %s\" % bin_path) return bin_path # get_semver_path() def semver_inc(version, level =",
"semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd =",
"qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read",
"preid for pre- levels. runs semver --increment <level> [--preid <preid>] <version> This does",
"= qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] =",
"<level> [--preid <preid>] <version> This does **not** do what you probably want... `preid`",
"import (absolute_import, division, print_function) __metaclass__ = type import subprocess import os import json",
"bin_path # get_semver_path() def semver_inc(version, level = None, preid = None): '''increment the",
"{ 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() #",
"division, print_function) __metaclass__ = type import subprocess import os import json import sys",
"# semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string)",
"not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" % bin_path) return bin_path #",
"get_semver_path() def semver_inc(version, level = None, preid = None): '''increment the version at",
"return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a file. '''",
"ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid =",
"version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] ==",
"stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT ) version = json.loads(out) version['is_release']",
"'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ] if",
"semver_inc() def semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' %",
"subprocess.check_output( cmd, cwd = qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease']) ==",
"''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd = ['node',",
"return version # semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version',",
"FilterModule(object): ''' version manipulation filters ''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse':",
"'qb_read_version': qb_read_version, } # filters() # FilterModule # testing - call camel_case on",
"''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version,",
"version return version # semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return",
"qb_read_version(file_path): '''Read a QB::Package::Version from a file. ''' with open(file_path, 'r') as file:",
"version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' ) if version['is_release']:",
"get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't",
"'1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0' The only way to get",
"if not (level is None): cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid)",
"level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse()",
"'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule # testing - call",
"qb_read_version, } # filters() # FilterModule # testing - call camel_case on first",
"''' with open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation",
"only way to get the `preid` appended is to increment the prerelease: >>>",
"semver --increment <level> [--preid <preid>] <version> This does **not** do what you probably",
"qb.ROOT ) version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = (",
"__future__ import (absolute_import, division, print_function) __metaclass__ = type import subprocess import os import",
"= 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ] if not (level",
") version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease'])",
"preid = None): '''increment the version at level, with optional preid for pre-",
"`preid` appended is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev')",
"semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) )",
"( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd = ['node', '--eval', stmt] out",
"= ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level']",
"on first cli arg and print result if __name__ == '__main__': import doctest",
"the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd = [",
"== 0 version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' )",
"out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. ''' stmt",
"= os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver",
"0 and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] = 'release' else: version['level']",
"import sys from ansible.errors import AnsibleError import qb from qb.ipc.rpc import client as",
"def semver_parse(version): '''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version)",
"'''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd = ['node', '--eval', stmt] out =",
"'''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a",
"version = json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) >",
"= json.loads(out) version['is_release'] = len(version['prerelease']) == 0 version['is_dev'] = ( len(version['prerelease']) > 0",
") if version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0] # depreciated name",
"for pre- levels. runs semver --increment <level> [--preid <preid>] <version> This does **not**",
"<preid>] <version> This does **not** do what you probably want... `preid` is ignored:",
"} # filters() # FilterModule # testing - call camel_case on first cli",
"semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid = 'dev') '1.1.0'",
"# filters() # FilterModule # testing - call camel_case on first cli arg",
"# FilterModule # testing - call camel_case on first cli arg and print",
"client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if",
"None): cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd)",
"version['level'] = 'release' else: version['level'] = version['prerelease'][0] # depreciated name for level version['type']",
"''' cmd = [ get_semver_path(), '--increment', ] if not (level is None): cmd.append(level)",
"return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters()",
"if version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0] # depreciated name for",
"None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version):",
"and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] = 'release' else: version['level'] =",
"'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a file. ''' with open(file_path,",
"cmd.append(level) if not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return",
"from qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver',",
"class FilterModule(object): ''' version manipulation filters ''' def filters(self): return { 'semver_inc': semver_inc,",
"filters ''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version':",
"0 version['is_dev'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' ) version['is_rc']",
"appended is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0'",
") cmd = ['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT",
"version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version",
"camel_case on first cli arg and print result if __name__ == '__main__': import",
"levels. runs semver --increment <level> [--preid <preid>] <version> This does **not** do what",
"is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor', preid",
"json import sys from ansible.errors import AnsibleError import qb from qb.ipc.rpc import client",
"'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" % bin_path) return",
"json.dumps(version) ) cmd = ['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd =",
"'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' )",
"AnsibleError import qb from qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path =",
"version['prerelease'][0] # depreciated name for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" %",
"import qb from qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT,",
"= \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def qb_version_parse(version_string): '''Parse version into",
"__metaclass__ = type import subprocess import os import json import sys from ansible.errors",
"version # semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from',",
"qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters ''' def filters(self): return { 'semver_inc':",
"open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters '''",
"do what you probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid =",
"name for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version",
"bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find",
"at level, with optional preid for pre- levels. runs semver --increment <level> [--preid",
"the `preid` appended is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid =",
"None, preid = None): '''increment the version at level, with optional preid for",
"len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease']) >",
"= subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. ''' stmt =",
"filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } #",
"FilterModule # testing - call camel_case on first cli arg and print result",
"version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def",
"<version> This does **not** do what you probably want... `preid` is ignored: >>>",
"'release' else: version['level'] = version['prerelease'][0] # depreciated name for level version['type'] = version['level']",
"semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(), '--increment', ]",
"depreciated name for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return",
"'1.1.0' The only way to get the `preid` appended is to increment the",
"def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise",
"at %s\" % bin_path) return bin_path # get_semver_path() def semver_inc(version, level = None,",
"a file. ''' with open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object): '''",
"level = None, preid = None): '''increment the version at level, with optional",
"first cli arg and print result if __name__ == '__main__': import doctest doctest.testmod()",
"want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0',",
"`preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid = 'dev') '1.0.1' >>> semver_inc('1.0.0', 'minor',",
"'--increment', ] if not (level is None): cmd.append(level) if not (preid is None):",
"rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a file. ''' with",
"= ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd = ['node', '--eval', stmt]",
"% version return version # semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version '''",
"QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a",
"version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from a file. ''' with open(file_path, 'r')",
"and version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease']) > 0 and version['prerelease'][0]",
"== 'rc' ) if version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0] #",
"with optional preid for pre- levels. runs semver --increment <level> [--preid <preid>] <version>",
"'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule",
"> 0 and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] = 'release' else:",
"not (preid is None): cmd.append('--preid') cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() #",
"version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def qb_version_parse(version_string): '''Parse",
"\"%(major)s.%(minor)s.%(patch)s\" % version return version # semver_parse() def qb_version_parse(version_string): '''Parse version into QB::Package::Version",
"None): '''increment the version at level, with optional preid for pre- levels. runs",
"( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' ) version['is_rc'] = ( len(version['prerelease'])",
"qb.ipc.rpc import client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin',",
"a QB::Package::Version from a file. ''' with open(file_path, 'r') as file: return qb_version_parse(file.read())",
"This does **not** do what you probably want... `preid` is ignored: >>> semver_inc('1.0.0',",
"semver_parse, 'qb_version_parse': qb_version_parse, 'qb_read_version': qb_read_version, } # filters() # FilterModule # testing -",
"= ['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT ) version",
"%s\" % bin_path) return bin_path # get_semver_path() def semver_inc(version, level = None, preid",
"( len(version['prerelease']) > 0 and version['prerelease'][0] == 'rc' ) if version['is_release']: version['level'] =",
"'node_modules', 'semver', 'bin', 'semver') if not os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\"",
"QB::Package::Version from a file. ''' with open(file_path, 'r') as file: return qb_version_parse(file.read()) class",
"for level version['type'] = version['level'] version['release'] = \"%(major)s.%(minor)s.%(patch)s\" % version return version #",
"import os import json import sys from ansible.errors import AnsibleError import qb from",
"to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd",
"return qb_version_parse(file.read()) class FilterModule(object): ''' version manipulation filters ''' def filters(self): return {",
"raise Exception(\"can't find semver at %s\" % bin_path) return bin_path # get_semver_path() def",
"subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver. ''' stmt = (",
"'''parse semver. ''' stmt = ( '''console.log(JSON.stringify(require('semver')(%s), null, 2))''' % json.dumps(version) ) cmd",
"null, 2))''' % json.dumps(version) ) cmd = ['node', '--eval', stmt] out = subprocess.check_output(",
"to get the `preid` appended is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease',",
"['node', '--eval', stmt] out = subprocess.check_output( cmd, cwd = qb.ROOT ) version =",
"import json import sys from ansible.errors import AnsibleError import qb from qb.ipc.rpc import",
"cmd.append(preid) cmd.append(version) out = subprocess.check_output(cmd) return out.rstrip() # semver_inc() def semver_parse(version): '''parse semver.",
"version['is_release']: version['level'] = 'release' else: version['level'] = version['prerelease'][0] # depreciated name for level",
"into QB::Package::Version ''' return rpc_client.send('QB::Package::Version', 'from', version_string) def qb_read_version(file_path): '''Read a QB::Package::Version from",
"Exception(\"can't find semver at %s\" % bin_path) return bin_path # get_semver_path() def semver_inc(version,",
"increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd =",
"= ( len(version['prerelease']) > 0 and version['prerelease'][0] == 'dev' ) version['is_rc'] = (",
"version['level'] = version['prerelease'][0] # depreciated name for level version['type'] = version['level'] version['release'] =",
"print_function) __metaclass__ = type import subprocess import os import json import sys from",
"'''increment the version at level, with optional preid for pre- levels. runs semver",
"# get_semver_path() def semver_inc(version, level = None, preid = None): '''increment the version",
"prerelease: >>> semver_inc('1.0.0', 'prerelease', preid = 'dev') '1.0.1-dev.0' ''' cmd = [ get_semver_path(),",
"version manipulation filters ''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse':",
"import client as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver')",
"manipulation filters ''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse, 'qb_version_parse': qb_version_parse,",
"get the `preid` appended is to increment the prerelease: >>> semver_inc('1.0.0', 'prerelease', preid",
"os.path.isfile(bin_path): raise Exception(\"can't find semver at %s\" % bin_path) return bin_path # get_semver_path()",
"semver_inc(version, level = None, preid = None): '''increment the version at level, with",
"[--preid <preid>] <version> This does **not** do what you probably want... `preid` is",
"''' version manipulation filters ''' def filters(self): return { 'semver_inc': semver_inc, 'semver_parse': semver_parse,",
"as rpc_client def get_semver_path(): bin_path = os.path.join(qb.ROOT, 'node_modules', 'semver', 'bin', 'semver') if not",
"from a file. ''' with open(file_path, 'r') as file: return qb_version_parse(file.read()) class FilterModule(object):",
"does **not** do what you probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch',",
"**not** do what you probably want... `preid` is ignored: >>> semver_inc('1.0.0', 'patch', preid"
] |
[] |
[
"3.2.9 on 2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'),",
"<reponame>Paul-W-0/FindContractors # Generated by Django 3.2.9 on 2021-12-01 22:00 from django.db import migrations",
"= [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [ migrations.RemoveField( model_name='profile', name='is_a_company', ), ]",
"on 2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp',",
"# Generated by Django 3.2.9 on 2021-12-01 22:00 from django.db import migrations class",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations",
"Django 3.2.9 on 2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [ migrations.RemoveField(",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations =",
"dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [ migrations.RemoveField( model_name='profile', name='is_a_company', ),",
"class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [ migrations.RemoveField( model_name='profile',",
"22:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ]",
"import migrations class Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [",
"Migration(migrations.Migration): dependencies = [ ('ContractorApp', '0010_rename_user_type_profile_is_a_company'), ] operations = [ migrations.RemoveField( model_name='profile', name='is_a_company',",
"Generated by Django 3.2.9 on 2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration):",
"by Django 3.2.9 on 2021-12-01 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies"
] |
[
"/ sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per",
"ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date,",
"= sum(r.sigma ** 2 for r in chain(team1, team2)) size = len(team1) +",
"fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0",
"in team1) - sum(r.mu for r in team2) sum_sigma = sum(r.sigma ** 2",
"{len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k, v in",
"else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi =",
"max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred:",
"0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step':",
"X_test = [] y_test = [] payouts = [] bet_amts = [] accuracy",
"for k, v in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue",
"test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling",
"bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52 #",
"not is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data)",
"f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi +=",
"{sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7,",
"features = SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)}) for k in",
"bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503",
"* 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis,",
"'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early',",
"considered as current best estimate of the optimum') print(list(es.result[5])) else: main(params) if __name__",
"for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('')",
"+ 1) # actual outcome pred_flipped = False if 'bet' in fight: is_actual_correct",
"import BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor from .data import DATA",
"sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds >",
"sum(bet_amts) res = -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi *",
"bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88 #",
"/ f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi",
"= f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0,",
"max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size *",
"from trueskill import BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor from .data",
"drawn=drawn) ################################### # train if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not",
"f1_ts + f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma * 2 #",
"round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred >",
"X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct = 0 payout = -bet_size",
"return 100 / us_odds + 1 def to_implied_odds(us_odds: float) -> float: decimal_odds =",
"0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, #",
"'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0, 0,",
"1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions",
"-26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52 #",
"else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight",
"f1_odds - 1 / f2_odds else: f_odds = 1 / f2_odds - 1",
"hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a =",
"train=1) for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best')",
"= f1_ts + f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma * 2",
"0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) -",
"space, to be considered as current best estimate of the optimum') print(list(es.result[5])) else:",
"* 2 f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max = f1_ts +",
"/ f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi =",
"ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma *",
"'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values'",
"update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training:",
"f1_odds * bet_size elif not is_win_1 and f2_pred > f1_pred: correct = 1",
"sortedcontainers import SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating from xgboost import",
"bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill",
"bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *=",
"= None scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date = None",
"> f1_pred: correct = 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds",
".data_2017 import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu",
"max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred:",
"accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:')",
"hyper_params reg_params = { 'n_estimators': 100 if train else 1000, # 'learning_rate': 0.09426181829690375,",
"len(params) == len(names) # assert len(params) == len(bounds[0]) if train: sigma = 1",
"f1_pred > f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser",
"100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day:",
"f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1,",
"= np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}')",
"multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1]",
"########################################## # update data if 'winner' in fight: # get winner fw =",
"bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred: f_ts = f1_ts -",
"bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in fight and fight['prediction'] is",
"day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) -",
"= f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts)",
"if train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, #",
"= -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init",
"reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg =",
"f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1,",
"* fight['bet'] else: fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet'])",
"# 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params",
"= fight['prediction'] == fw actual = (actual[0] + is_actual_correct, actual[1] + 1) cash",
"# -72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a",
"scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for",
"training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff',",
"else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi =",
"f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser =",
"y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set,",
"-> float: decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError: return",
"= (0, 0) actual_debug = [] bet_multis = [] bet_multis_cat = [] preds_flipped",
"fitness = [main(x, train=1) for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5]))",
"denom) def to_decimal_odds(us_odds): if us_odds > 0: return us_odds / 100 + 1",
"f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min -",
"bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi",
"reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main training')",
"reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1 # pred max if f1_pred",
"[(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params)",
"# loop through scenes for i, scene in enumerate(all_data): is_training = i <",
"> 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab)",
"+= bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred: f_ts = f1_ts",
"# wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1]))",
"= get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params()",
"= f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a,",
"f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped))",
"win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts,",
"round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred >",
"2 f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma",
"f1_pred exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner =",
"scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100 if train else 1000, #",
"with your bets elif 'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}') continue",
"= f1_odds if is_win_1 else f2_odds cash += fw_odds * fight['bet'] else: fw_odds",
"= -26.933801584409544 # init reg = None scaler = MinMaxScaler() cutoff = int(len(all_data)",
"cutoff = int(len(all_data) * 0.6) start_date = None ratings = defaultdict(lambda: Rating()) wins_losses",
"f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}%",
"sheet) > 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff",
"f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1],",
"bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred: f_odds =",
"sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from trueskill import BETA,",
"log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}%",
"inopts=opts) while not es.stop(): solutions = es.ask() fitness = [main(x, train=1) for x",
"delta_mu = sum(r.mu for r in team1) - sum(r.mu for r in team2)",
"f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi",
"is_win_1 else f1 if not is_win_1 and fw != f2 and fw is",
"def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set =",
"rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds',",
"f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] /",
"= -50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60",
"itertools import chain from random import random import numpy as np from cma",
"{actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}')",
"${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet) > 0.01: for l in",
"'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a,",
"if us_odds > 0: return us_odds / 100 + 1 else: return 100",
"f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi)))",
"XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def",
"0) actual_debug = [] bet_multis = [] bet_multis_cat = [] preds_flipped = []",
"continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu",
"0, 0, 0, 0, 0 ] bounds = [[-np.inf], [np.inf]] assert len(params) ==",
"global_env, rate_1vs1, Rating from xgboost import XGBRegressor from .data import DATA from .data_2016",
"0: return us_odds / 100 + 1 else: return 100 / us_odds +",
"# bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 #",
"f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi)))",
"reg = None scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date =",
"f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma",
"/ sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days",
"max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = {",
"from datetime import datetime from collections import Counter, defaultdict, OrderedDict from itertools import",
"= np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) /",
"{ 'n_estimators': 100 if train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 #",
"mean in \"phenotype\" space, to be considered as current best estimate of the",
"'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0,",
"and f2_pred > f1_pred: correct = 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds",
"if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred",
"'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [",
"defaultdict(lambda: 0.5) X_train = [] y_train = [] X_test = [] y_test =",
"while not es.stop(): solutions = es.ask() fitness = [main(x, train=1) for x in",
"if f1_pred > f2_pred: f_odds = 1 / f1_odds - 1 / f2_odds",
"max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma,",
"# good luck with your bets elif 'winner' not in fight: logger.warning(f'Pending {f1}",
"if is_win_1 else f2_odds cash += fw_odds * fight['bet'] else: fw_odds = f2_odds",
"tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab)",
"{Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]}",
"pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser = f1",
"= hyper_params reg_params = { 'n_estimators': 100 if train else 1000, # 'learning_rate':",
"-26.933801584409544 # init reg = None scaler = MinMaxScaler() cutoff = int(len(all_data) *",
"not -50 < f2_odds < 50: raise ValueError(f'surely these odds are wrong? {f1_odds}",
"{bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in fight and fight['prediction']",
"get winner fw = fight['winner']['fighter'] is_win_1 = fw == f1 fl = f2",
"else: fw_pred = f2_pred fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1,",
"= f2_pred fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1])",
"[f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max",
"logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit",
"f1_odds < 50 or not -50 < f2_odds < 50: raise ValueError(f'surely these",
"preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred *",
"sheet = -62.62 if abs(sum(tab) - sheet) > 0.01: for l in actual_debug:",
"math import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from trueskill",
"] ########################################## # update data if 'winner' in fight: # get winner fw",
"f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b],",
"round(bet_size * bet_multi) assert bet_amt >= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size)",
"+ DATA_2018 + DATA # estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight",
"100 if train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791,",
"f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi",
"bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat,",
"import MinMaxScaler from sortedcontainers import SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating",
"= (f1_pred > f2_pred and fight['prediction'] != f1) or ( f2_pred > f1_pred",
"len(names) # assert len(params) == len(bounds[0]) if train: sigma = 1 opts =",
"= None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda:",
"reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params =",
"'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a",
"bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred > f2_pred: f_wnl",
"${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet)",
"from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for r in",
"= f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0,",
"2 for r in chain(team1, team2)) size = len(team1) + len(team2) denom =",
"reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size",
"bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi",
"f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min,",
"import datetime from collections import Counter, defaultdict, OrderedDict from itertools import chain from",
"XGBRegressor from .data import DATA from .data_2016 import DATA_2016 from .data_2017 import DATA_2017",
"fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred,",
"* 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser}",
"team2)) size = len(team1) + len(team2) denom = sqrt(size * (BETA * BETA)",
"if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred *",
"'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_),",
"y_test = [] payouts = [] bet_amts = [] accuracy = (0, 0)",
"made if 'prediction' in fight and fight['prediction'] is None: if f1_pred > f2_pred:",
"= [main(x, train=1) for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty()",
"def main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016 + DATA_2017 + DATA_2018",
"print('xfavorite: distribution mean in \"phenotype\" space, to be considered as current best estimate",
"solutions = es.ask() fitness = [main(x, train=1) for x in solutions] es.tell(solutions, fitness)",
"summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg,",
"f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner =",
"# opts['tolx'] = 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while",
"- f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi",
"logger.info('Starting main training') all_data = DATA_2016 + DATA_2017 + DATA_2018 + DATA #",
"bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill",
"opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions =",
"f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate,",
"y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test",
"= (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per",
"'prediction' in fight and fight['prediction'] is None: if f1_pred > f2_pred: exp_winner =",
"scenes for i, scene in enumerate(all_data): is_training = i < cutoff if not",
"= f2_ts - f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma * 2",
"are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) #",
"# -3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52 # -8.01",
"actual = (actual[0] + is_actual_correct, actual[1] + 1) cash = -fight['bet'] if is_actual_correct:",
"Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now()",
"1 last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn)",
"!= {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train = 0 names =",
"correct = 1 payout += f1_odds * bet_size elif not is_win_1 and f2_pred",
"round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred >",
"f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data if 'winner' in fight:",
"= [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last',",
"= f2 if is_win_1 else f1 if not is_win_1 and fw != f2",
"round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt >= 1, f'bet multi is",
"fight['winner']['fighter'] is_win_1 = fw == f1 fl = f2 if is_win_1 else f1",
"f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data if 'winner'",
"f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds,",
"# -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52 #",
"if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data",
"[] accuracy = (0, 0) tab = [] tab_amts = [] actual =",
"bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train,",
"= [ 0, 0, 0, 0, 0, 0 ] bounds = [[-np.inf], [np.inf]]",
"f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1],",
"f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1],",
"/ f1_odds - 1 / f2_odds else: f_odds = 1 / f2_odds -",
">= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made",
"${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per",
"f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max = f2_ts",
"X_train = [] y_train = [] X_test = [] y_test = [] payouts",
"drawn = fw is None # update wins losses wins_losses[f1] += [1] wins_losses[f2]",
"if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%')",
"print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy,",
"bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg =",
"bet_amt = round(bet_size * bet_multi) assert bet_amt >= 1, f'bet multi is fucked:",
"100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance}",
"actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \"",
"'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses',",
"CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions = es.ask() fitness = [main(x, train=1)",
"min if f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min =",
"= f1_pred exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner",
"f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}')",
"vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs",
"= np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}')",
"def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds",
"win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses",
"f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct",
"bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b",
"= -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg = None scaler = MinMaxScaler()",
"tab_amts = [] actual = (0, 0) actual_debug = [] bet_multis = []",
"elif not is_win_1 and f2_pred > f1_pred: correct = 1 payout += f2_odds",
"round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred >",
"f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2],",
"bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred: f_ts",
"main training') all_data = DATA_2016 + DATA_2017 + DATA_2018 + DATA # estimators,",
"early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 # update ratings ratings[fw],",
"np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes if t >",
"< f2_odds < 50: raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob",
"for r in team1) - sum(r.mu for r in team2) sum_sigma = sum(r.sigma",
"f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred > f2_pred and",
"print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space,",
"len(team1) + len(team2) denom = sqrt(size * (BETA * BETA) + sum_sigma) ts",
"diff if f1_pred > f2_pred: f_odds = 1 / f1_odds - 1 /",
"from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from trueskill import BETA, global_env,",
"actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test,",
"> f2_pred and fight['prediction'] != f1) or ( f2_pred > f1_pred and fight['prediction']",
"sigma = 1 opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds",
"f1_pred: correct = 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and",
"'bet_tma_b', ] params = [ 0, 0, 0, 0, 0, 0 ] bounds",
"assert bet_amt >= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# #",
"> f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min",
"{Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] *",
"if f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max",
"# pred max if f1_pred > f2_pred: f_pred = f1_pred - f2_pred else:",
"= f1_ts - f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a,",
"tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction']",
"fight['prediction'] is None: if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner = f1_pred",
"return res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts,",
"win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1])",
"days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f}",
"f2_ts_max = f2_ts + f2_sigma * 2 # odds data f1_odds = fight['odds'][f1]",
"bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred: f_odds",
"reg def main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016 + DATA_2017 +",
"get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num",
"/ len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) *",
"= reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main",
"= f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome",
"np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts)",
"-72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a =",
"= 1 / f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0]",
"exp_winner = f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser = f2_pred else:",
"as current best estimate of the optimum') print(list(es.result[5])) else: main(params) if __name__ ==",
"0.5) X_train = [] y_train = [] X_test = [] y_test = []",
"= fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 < f1_odds < 50 or",
"bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b",
"fw actual = (actual[0] + is_actual_correct, actual[1] + 1) cash = -fight['bet'] if",
"on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with",
"log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred}",
"summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree",
"/ days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet) >",
"logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if",
"beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your bets elif",
"# test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet",
"+ 1) cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1 else",
"# 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a =",
"and fw is not None: raise ValueError(f'unknown winner {fw}') drawn = fw is",
"odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%')",
"logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names =",
"= [] bet_multis_cat = [] preds_flipped = [] odds_outcomes = [] # loop",
"= round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred",
"> f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance",
"reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts)",
"from .data_2017 import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu =",
"= win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses =",
"= f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a,",
"{params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts',",
"# update data if 'winner' in fight: # get winner fw = fight['winner']['fighter']",
"fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu",
"= fight['winner']['fighter'] is_win_1 = fw == f1 fl = f2 if is_win_1 else",
"payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') #",
"is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1] + 1) # actual",
"15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 #",
"except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('')",
"= [] bet_multis = [] bet_multis_cat = [] preds_flipped = [] odds_outcomes =",
"else: f_odds = 1 / f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a,",
"bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min",
"-50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60 #",
"in enumerate(all_data): is_training = i < cutoff if not is_training: if not reg:",
"outcome pred_flipped = False if 'bet' in fight: is_actual_correct = fight['prediction'] == fw",
"f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1 # pred",
"or ( f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]}",
"# max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100 if train",
"import chain from random import random import numpy as np from cma import",
"import numpy as np from cma import CMAEvolutionStrategy, CMAOptions from loguru import logger",
"# init reg = None scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6)",
"fw is not None: raise ValueError(f'unknown winner {fw}') drawn = fw is None",
"= [] tab_amts = [] actual = (0, 0) actual_debug = [] bet_multis",
"+ DATA # estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight = hyper_params",
"ValueError(f'unknown winner {fw}') drawn = fw is None # update wins losses wins_losses[f1]",
"if no odds: if 'odds' not in fight: continue f1 = fight['fighters'][0]['name'] f2",
"f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi",
"= SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)}) for k in features.keys():",
"f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min = f2_ts",
"days = (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet",
"X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train,",
"f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts -",
"-4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a",
"if train: total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts) res = -roi",
"import DATA from .data_2016 import DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import",
"in fight: is_actual_correct = fight['prediction'] == fw actual = (actual[0] + is_actual_correct, actual[1]",
"from loguru import logger from math import sqrt from sklearn.preprocessing import MinMaxScaler from",
"logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score =",
"exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%]",
"f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi",
"f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser = f2_pred",
"-16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96",
"run(): train = 0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a',",
"bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis,",
"bets elif 'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1:",
"datetime import datetime from collections import Counter, defaultdict, OrderedDict from itertools import chain",
"{actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days =",
"= defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train =",
"get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train),",
"f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min",
"defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train = [] y_train = [] X_test",
"update wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1] # update fights early_fights[fw]",
"start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg",
"(total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res",
"None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5)",
"reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k, v in zip(feature_names,",
"import XGBRegressor from .data import DATA from .data_2016 import DATA_2016 from .data_2017 import",
"/ days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]:",
"0) tab = [] tab_amts = [] actual = (0, 0) actual_debug =",
"= 1 # skip if no odds: if 'odds' not in fight: continue",
"f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max,",
"to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train,",
"'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0, 0, 0, 0,",
"[] bet_multis_cat = [] preds_flipped = [] odds_outcomes = [] # loop through",
"odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout,",
"+ f2_sigma * 2 # odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2]",
"* bet_size elif not is_win_1 and f2_pred > f1_pred: correct = 1 payout",
"logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score",
"f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1],",
"f_ts = f1_ts - f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi =",
"opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params,",
"actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual,",
"{sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train = 0 names = [",
"f2_odds = fight['odds'][f2] if not -50 < f1_odds < 50 or not -50",
"bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert",
"bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred: f_ts_max",
"bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds",
"wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train",
"trueskill min if f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min",
"from random import random import numpy as np from cma import CMAEvolutionStrategy, CMAOptions",
"= f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser",
"0, 0, 0, 0 ] bounds = [[-np.inf], [np.inf]] assert len(params) == len(names)",
"actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI",
"bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate -",
"2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction'] !=",
"ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights",
"start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date,",
"f2 pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser =",
"sum_sigma = sum(r.sigma ** 2 for r in chain(team1, team2)) size = len(team1)",
"and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\"",
"print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space, to be considered as",
"start_date = None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights =",
"# -8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a =",
"values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)})",
"**reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test and",
"is_actual_correct = fight['prediction'] == fw actual = (actual[0] + is_actual_correct, actual[1] + 1)",
"= np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}')",
"correct = 0 payout = -bet_size if is_win_1 and f1_pred > f2_pred: correct",
"k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:')",
"1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44",
"# 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426,",
"bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if",
"return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds > 0: return us_odds /",
"continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t",
"odds diff if f1_pred > f2_pred: f_odds = 1 / f1_odds - 1",
"'~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins',",
"0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train",
"{fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts",
"/ denom) def to_decimal_odds(us_odds): if us_odds > 0: return us_odds / 100 +",
"datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params)",
"= f1_pred - f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a,",
"k for k, v in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}')",
"= DATA_2016 + DATA_2017 + DATA_2018 + DATA # estimators, learning_rate = hyper_params",
"if is_win_1 and f1_pred > f2_pred: correct = 1 payout += f1_odds *",
"f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate,",
"None: if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser =",
"f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi",
"> f2_pred: correct = 1 payout += f1_odds * bet_size elif not is_win_1",
"bet scaling bet_multi = 1 # pred max if f1_pred > f2_pred: f_pred",
"f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data if 'winner' in fight: #",
"= [[-np.inf], [np.inf]] assert len(params) == len(names) # assert len(params) == len(bounds[0]) if",
"DATA # estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight = hyper_params #",
"Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab)",
"len(team2) denom = sqrt(size * (BETA * BETA) + sum_sigma) ts = global_env()",
"{ratings[exp_loser].mu:.0f}]') continue # good luck with your bets elif 'winner' not in fight:",
"bet_amt >= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction",
"f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b],",
"SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}:",
"early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data",
"bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi)",
"not None: raise ValueError(f'unknown winner {fw}') drawn = fw is None # update",
"1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set",
"round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred",
"multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy",
"+= f1_odds * bet_size elif not is_win_1 and f2_pred > f1_pred: correct =",
"scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1 #",
"f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate,",
"sum(r.mu for r in team1) - sum(r.mu for r in team2) sum_sigma =",
"train=0): logger.info('Starting main training') all_data = DATA_2016 + DATA_2017 + DATA_2018 + DATA",
"f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2],",
"f2_pred: f_pred = f1_pred - f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi",
"f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b],",
"t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts)",
"solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution",
"-fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds cash += fw_odds",
"assert len(params) == len(bounds[0]) if train: sigma = 1 opts = CMAOptions() #",
"is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else:",
"'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, #",
"[] payouts = [] bet_amts = [] accuracy = (0, 0) tab =",
"- f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi",
"= f2_pred else: fw_pred = f2_pred fl_pred = f1_pred # add test data",
"1 payout += f1_odds * bet_size elif not is_win_1 and f2_pred > f1_pred:",
"in fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts",
"wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1] # update fights early_fights[fw] =",
"= [] odds_outcomes = [] # loop through scenes for i, scene in",
"= 1 # pred max if f1_pred > f2_pred: f_pred = f1_pred -",
"bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749",
"= get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size =",
"[ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate",
"0, 0 ] bounds = [[-np.inf], [np.inf]] assert len(params) == len(names) # assert",
"= -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit",
"logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat",
"*= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt >= 1, f'bet multi",
"from math import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from",
"/ decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get",
"t in odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}%",
"bet_amts = [] accuracy = (0, 0) tab = [] tab_amts = []",
"if 'bet' in fight: is_actual_correct = fight['prediction'] == fw actual = (actual[0] +",
"logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)}) for",
"ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts",
"{fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred =",
"pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on",
"# 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337,",
"- f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0]",
"[]) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train = [] y_train",
"len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [",
"100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue #",
"actual = (0, 0) actual_debug = [] bet_multis = [] bet_multis_cat = []",
"f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser *",
"* 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]'",
"fw is None # update wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1]",
"hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100 if",
"and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train,",
"# assert len(params) == len(bounds[0]) if train: sigma = 1 opts = CMAOptions()",
"] bounds = [[-np.inf], [np.inf]] assert len(params) == len(names) # assert len(params) ==",
"pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs",
"[f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff",
"# skip if no odds: if 'odds' not in fight: continue f1 =",
"f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [",
"if is_win_1: fw_pred = f1_pred fl_pred = f2_pred else: fw_pred = f2_pred fl_pred",
"ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training",
"**reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0):",
"else: f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi =",
"= len(team1) + len(team2) denom = sqrt(size * (BETA * BETA) + sum_sigma)",
"0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b =",
"f1_ts - f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b],",
"not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1] + 1) #",
"in team2) sum_sigma = sum(r.sigma ** 2 for r in chain(team1, team2)) size",
"'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481,",
"f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2]))",
"+= fw_odds * fight['bet'] else: fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash,",
"if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser = f2",
"* 0.6) start_date = None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: [])",
"is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred >",
"- f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0]",
"'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins',",
"all_data = DATA_2016 + DATA_2017 + DATA_2018 + DATA # estimators, learning_rate =",
"is not None: raise ValueError(f'unknown winner {fw}') drawn = fw is None #",
"is None: if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser",
"fw_pred = f2_pred fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not",
"= f1_ts - f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma * 2",
"chain from random import random import numpy as np from cma import CMAEvolutionStrategy,",
"= -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg = None",
"f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ]",
"DATA_2016 + DATA_2017 + DATA_2018 + DATA # estimators, learning_rate = hyper_params #",
"= CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma,",
"100 + 1 else: return 100 / us_odds + 1 def to_implied_odds(us_odds: float)",
"= 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or",
"if f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate",
"and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1] + 1)",
"bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred: f_ts_max = f1_ts_max -",
"bet_ts_a = -50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756 #",
"accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes",
"bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds > f1_odds and not is_win_1)))",
"per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet) > 0.01: for",
"= global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds > 0: return",
"{accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days =",
"f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi",
"logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:')",
"gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params =",
"{cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred",
"and fw != f2 and fw is not None: raise ValueError(f'unknown winner {fw}')",
"SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor from",
"== fw actual = (actual[0] + is_actual_correct, actual[1] + 1) cash = -fight['bet']",
"= defaultdict(lambda: 0.5) X_train = [] y_train = [] X_test = [] y_test",
"fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in fight and",
"len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k",
"import SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor",
"\"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test and y_test:",
"from collections import Counter, defaultdict, OrderedDict from itertools import chain from random import",
"[-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1",
"actual_debug = [] bet_multis = [] bet_multis_cat = [] preds_flipped = [] odds_outcomes",
"these odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]],",
"raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob",
"win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] /",
"f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1 # pred max",
"0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b,",
"100 / us_odds + 1 def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds)",
"is_win_1 and f1_pred > f2_pred: correct = 1 payout += f1_odds * bet_size",
"bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred: f_ts_max =",
"bet_ts_b = -69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b",
"subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100 if train else 1000,",
"X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred",
"win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts,",
"bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b =",
"cma import CMAEvolutionStrategy, CMAOptions from loguru import logger from math import sqrt from",
"in chain(team1, team2)) size = len(team1) + len(team2) denom = sqrt(size * (BETA",
"us_odds + 1 def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return",
"import CMAEvolutionStrategy, CMAOptions from loguru import logger from math import sqrt from sklearn.preprocessing",
"bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses",
"losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl =",
"# -26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52",
"is_win_1: fw_pred = f1_pred fl_pred = f2_pred else: fw_pred = f2_pred fl_pred =",
"= 0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### #",
"= -10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b",
"f1_odds if is_win_1 else f2_odds cash += fw_odds * fight['bet'] else: fw_odds =",
"f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma *",
"!= f2 and fw is not None: raise ValueError(f'unknown winner {fw}') drawn =",
"np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') #",
"is_win_1) or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0]",
"-45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg",
"train: sigma = 1 opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] =",
"us_odds / 100 + 1 else: return 100 / us_odds + 1 def",
"trueskill import BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor from .data import",
"* 2 f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max = f2_ts +",
"(0, 0) tab = [] tab_amts = [] actual = (0, 0) actual_debug",
"= round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if",
"= last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl]",
"if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI",
"[f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu",
"bet_size elif not is_win_1 and f2_pred > f1_pred: correct = 1 payout +=",
"Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5)",
"{exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your bets elif 'winner'",
"* BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds):",
"f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma,",
"f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1,",
"tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab,",
"[] actual = (0, 0) actual_debug = [] bet_multis = [] bet_multis_cat =",
"# 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), #",
"* 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per",
"current best estimate of the optimum') print(list(es.result[5])) else: main(params) if __name__ == '__main__':",
"in \"phenotype\" space, to be considered as current best estimate of the optimum')",
"# trueskill mu if f1_pred > f2_pred: f_ts = f1_ts - f2_ts else:",
"= f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a,",
"return 1 / decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None,",
"if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train)",
"'%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('')",
"= np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}')",
"fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma",
"'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert",
"bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if",
"bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate",
"'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early',",
"logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train =",
"= f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]}",
"import random import numpy as np from cma import CMAEvolutionStrategy, CMAOptions from loguru",
"bet_multi = 1 # pred max if f1_pred > f2_pred: f_pred = f1_pred",
"for r in team2) sum_sigma = sum(r.sigma ** 2 for r in chain(team1,",
"{fw}') drawn = fw is None # update wins losses wins_losses[f1] += [1]",
"if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test",
"f2_pred > f1_pred: correct = 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds <",
"per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab =",
"# add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct =",
"train = 0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b',",
"= f2_ts + f2_sigma * 2 # odds data f1_odds = fight['odds'][f1] f2_odds",
"- f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1],",
"bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 #",
"tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts,",
"'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate',",
"- f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1],",
"exp_winner = f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner",
"1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if",
"{f1} vs {f2}') continue if is_win_1: fw_pred = f1_pred fl_pred = f2_pred else:",
"- 1 / f2_odds else: f_odds = 1 / f2_odds - 1 /",
"= fw is None # update wins losses wins_losses[f1] += [1] wins_losses[f2] +=",
"y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size = 1 #",
"0.5) last_fights = defaultdict(lambda: 0.5) X_train = [] y_train = [] X_test =",
"f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts,",
"luck with your bets elif 'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}')",
"features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k,",
"best estimate of the optimum') print(list(es.result[5])) else: main(params) if __name__ == '__main__': run()",
"to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds except",
"1 / f1_odds - 1 / f2_odds else: f_odds = 1 / f2_odds",
"float: decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError: return 1",
"return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...')",
"- f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0]",
"sqrt(size * (BETA * BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu /",
"- f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1],",
"eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016",
"print('') print('xfavorite: distribution mean in \"phenotype\" space, to be considered as current best",
"f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi =",
"cutoff if not is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale",
"{f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data",
"2 # odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50",
"= (0, 0) tab = [] tab_amts = [] actual = (0, 0)",
"f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate,",
"bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet) > 0.01: for l",
"verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016 +",
"-12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01",
"= f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner *",
"learning_rate = hyper_params # gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight",
"data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2])",
"for i, scene in enumerate(all_data): is_training = i < cutoff if not is_training:",
"= -62.62 if abs(sum(tab) - sheet) > 0.01: for l in actual_debug: logger.warning(l)",
"bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93",
"outcome correct = 0 payout = -bet_size if is_win_1 and f1_pred > f2_pred:",
"- datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}')",
"# -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params",
"[] # loop through scenes for i, scene in enumerate(all_data): is_training = i",
"np from cma import CMAEvolutionStrategy, CMAOptions from loguru import logger from math import",
"x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck",
"pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]'",
"from itertools import chain from random import random import numpy as np from",
"f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2",
"estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate:",
"bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88",
"{-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts,",
"{k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for",
"in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data)",
"f_odds = 1 / f1_odds - 1 / f2_odds else: f_odds = 1",
"enumerate(all_data): is_training = i < cutoff if not is_training: if not reg: start_date",
"[{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your bets elif 'winner' not",
"1) cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds",
"f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance =",
"wins and losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else:",
"# gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params",
"'~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) ==",
"bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318",
"if 'winner' in fight: # get winner fw = fight['winner']['fighter'] is_win_1 = fw",
"= rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training: if 'winner' in fight:",
"= 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 #",
"logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} =",
"sum(r.mu for r in team2) sum_sigma = sum(r.sigma ** 2 for r in",
"> f2_pred: f_odds = 1 / f1_odds - 1 / f2_odds else: f_odds",
"else: f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi =",
"or not -50 < f2_odds < 50: raise ValueError(f'surely these odds are wrong?",
"if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg =",
"Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good",
"f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts,",
"{sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train = 0 names",
"odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 < f1_odds",
"f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction'",
"not in fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred = f1_pred",
"names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a',",
"losses wins_losses[f1] += [1] wins_losses[f2] += [-1] # update fights early_fights[fw] = last_fights[fw]",
"'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ]",
"# -3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 # bet_ts_a,",
"accuracy = (0, 0) tab = [] tab_amts = [] actual = (0,",
"2 f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma",
"len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features =",
"f1 fl = f2 if is_win_1 else f1 if not is_win_1 and fw",
"= defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train = [] y_train = []",
"0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b',",
"logger from math import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict",
"bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill",
"f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else",
"fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 < f1_odds < 50 or not",
"from cma import CMAEvolutionStrategy, CMAOptions from loguru import logger from math import sqrt",
"sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit:",
"wins_losses[f1] += [1] wins_losses[f2] += [-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl]",
"== len(names) # assert len(params) == len(bounds[0]) if train: sigma = 1 opts",
"bounds = [[-np.inf], [np.inf]] assert len(params) == len(names) # assert len(params) == len(bounds[0])",
"tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test, y_test,",
"f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max = f1_ts",
"cash += fw_odds * fight['bet'] else: fw_odds = f2_odds if is_win_1 else f1_odds",
"# 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b',",
"day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}')",
"scene['fights']: bet_size = 1 # skip if no odds: if 'odds' not in",
"bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab)",
"f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min",
"# reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params",
"1 else: return 100 / us_odds + 1 def to_implied_odds(us_odds: float) -> float:",
"fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in",
"'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } #",
"3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52",
"= ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min = f2_ts -",
"f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2],",
"early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds,",
"in scene['fights']: bet_size = 1 # skip if no odds: if 'odds' not",
"vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi =",
"= f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0,",
"fl = f2 if is_win_1 else f1 if not is_win_1 and fw !=",
"f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi",
"3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a,",
"# update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if",
"if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t in",
"from sortedcontainers import SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating from xgboost",
"-3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b",
"'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0, 0, 0, 0, 0",
"'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params =",
"if not is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train)",
"# train if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ###################################",
"f1 if not is_win_1 and fw != f2 and fw is not None:",
"{fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred",
"reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting",
"= 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 #",
"f2_pred fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) #",
"50 or not -50 < f2_odds < 50: raise ValueError(f'surely these odds are",
"es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions = es.ask() fitness =",
"payout = -bet_size if is_win_1 and f1_pred > f2_pred: correct = 1 payout",
"denom = sqrt(size * (BETA * BETA) + sum_sigma) ts = global_env() return",
"scaling bet_multi = 1 # pred max if f1_pred > f2_pred: f_pred =",
"training') all_data = DATA_2016 + DATA_2017 + DATA_2018 + DATA # estimators, learning_rate",
"be considered as current best estimate of the optimum') print(list(es.result[5])) else: main(params) if",
"bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in fight and fight['prediction'] is None:",
"# bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 #",
"{roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date, bet_amts,",
"* 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now()",
"exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred",
"= int(len(all_data) * 0.6) start_date = None ratings = defaultdict(lambda: Rating()) wins_losses =",
"f1_pred - f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b],",
"\"phenotype\" space, to be considered as current best estimate of the optimum') print(list(es.result[5]))",
"accuracy = (accuracy[0] + correct, accuracy[1] + 1) # actual outcome pred_flipped =",
"bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred: f_ts = f1_ts - f2_ts",
"+= bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred: f_ts_min = f1_ts_min",
"hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b = -69.5794588139756",
"is None # update wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1] #",
"# odds diff if f1_pred > f2_pred: f_odds = 1 / f1_odds -",
"f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1],",
"losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses =",
"# 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight':",
"and is_win_1) or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy =",
"logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat",
"= -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 #",
"= { 'n_estimators': 100 if train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264",
"fw_pred = f1_pred fl_pred = f2_pred else: fw_pred = f2_pred fl_pred = f1_pred",
"[ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1,",
"len(bounds[0]) if train: sigma = 1 opts = CMAOptions() # opts['tolx'] = 1E-2",
"sum(payouts) roi = total_payouts / sum(bet_amts) res = -roi - (total_payouts / 5000)",
"prediction made if 'prediction' in fight and fight['prediction'] is None: if f1_pred >",
"as np from cma import CMAEvolutionStrategy, CMAOptions from loguru import logger from math",
"2 f2_ts_max = f2_ts + f2_sigma * 2 # odds data f1_odds =",
"/ max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data",
"opts['tolx'] = 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not",
"{odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() -",
"logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts',",
"= fw == f1 fl = f2 if is_win_1 else f1 if not",
"diff {sum(tab) - sheet:.2f}') def run(): train = 0 names = [ #",
"f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi +=",
"# actual outcome pred_flipped = False if 'bet' in fight: is_actual_correct = fight['prediction']",
"'~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate',",
"- f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ],",
"np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') #",
"assert len(params) == len(names) # assert len(params) == len(bounds[0]) if train: sigma =",
"* 2 # odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not",
"last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 # update ratings",
"scene in enumerate(all_data): is_training = i < cutoff if not is_training: if not",
"in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run():",
"# bet scaling bet_multi = 1 # pred max if f1_pred > f2_pred:",
"f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to",
"f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max -",
"100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() -",
"vs {f2}') continue if is_win_1: fw_pred = f1_pred fl_pred = f2_pred else: fw_pred",
"f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma *",
"f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data if 'winner' in",
"elif 'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred",
"{fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train:",
"-4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17",
"start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train,",
"max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100 if train else",
"if abs(sum(tab) - sheet) > 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f}",
"(actual[0] + is_actual_correct, actual[1] + 1) cash = -fight['bet'] if is_actual_correct: fw_odds =",
"f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate bet_wnl_multi =",
"[1] wins_losses[f2] += [-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl]",
"= -bet_size if is_win_1 and f1_pred > f2_pred: correct = 1 payout +=",
"1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth':",
"= MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date = None ratings = defaultdict(lambda:",
"False if 'bet' in fight: is_actual_correct = fight['prediction'] == fw actual = (actual[0]",
"in fight and fight['prediction'] is None: if f1_pred > f2_pred: exp_winner = f1",
"= sum(payouts) roi = total_payouts / sum(bet_amts) res = -roi - (total_payouts /",
"f2_ts - f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max",
"{log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts) res",
"################################### # train if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1])",
"{params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%',",
"odds_acc = sum([t for t in odds_outcomes if t > 0]) / len(odds_outcomes)",
"{params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma',",
"in odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds:",
"team1) - sum(r.mu for r in team2) sum_sigma = sum(r.sigma ** 2 for",
"1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi)))",
"'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0, 0, 0,",
"2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422",
"bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi",
"fight: is_actual_correct = fight['prediction'] == fw actual = (actual[0] + is_actual_correct, actual[1] +",
"from .data_2016 import DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import DATA_2018 def",
"y_train = [] X_test = [] y_test = [] payouts = [] bet_amts",
"(0, 0) actual_debug = [] bet_multis = [] bet_multis_cat = [] preds_flipped =",
"f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi +=",
"f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi",
"+ correct, accuracy[1] + 1) # actual outcome pred_flipped = False if 'bet'",
"es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean",
"is_win_1]) # testing outcome correct = 0 payout = -bet_size if is_win_1 and",
"eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main training') all_data =",
"update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] =",
"f2_ts, f1_ts_max - f2_ts_max, last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1],",
"# 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample':",
"len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min",
"- f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max =",
"- (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return",
"# update wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1] # update fights",
"and losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl",
"'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred =",
"x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('')",
"fw = fight['winner']['fighter'] is_win_1 = fw == f1 fl = f2 if is_win_1",
"data if 'winner' in fight: # get winner fw = fight['winner']['fighter'] is_win_1 =",
"es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\"",
"= [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4,",
"= f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs",
"fight and fight['prediction'] is None: if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner",
"odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes):",
"loop through scenes for i, scene in enumerate(all_data): is_training = i < cutoff",
"pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner = f2",
"correct = 1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1)",
"{fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if",
"fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts =",
"logger.info(f'Features:') features = SortedDict({v: k for k, v in zip(feature_names, reg.feature_importances_)}) for k",
"reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}')",
"= f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0,",
"model...') eval_set = [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg =",
"per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab)",
"= [] accuracy = (0, 0) tab = [] tab_amts = [] actual",
"> f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1]",
"-8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b,",
"logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred = f1_pred fl_pred = f2_pred",
"data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma",
"is_win_1 and fw != f2 and fw is not None: raise ValueError(f'unknown winner",
"update data if 'winner' in fight: # get winner fw = fight['winner']['fighter'] is_win_1",
"train if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### #",
"f2 if is_win_1 else f1 if not is_win_1 and fw != f2 and",
"defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train = []",
"# pred flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction'] != f1) or",
"logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds',",
"{log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts)",
"eval_set = [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror',",
"wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins",
"print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space, to be considered",
"[ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts -",
"1 # pred max if f1_pred > f2_pred: f_pred = f1_pred - f2_pred",
"early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 #",
"= f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner}",
"= 1 / f1_odds - 1 / f2_odds else: f_odds = 1 /",
"= sqrt(size * (BETA * BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu",
"estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [",
"total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts) res = -roi - (total_payouts",
"payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts,",
"bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55",
"fight['prediction'] == fw actual = (actual[0] + is_actual_correct, actual[1] + 1) cash =",
".data_2016 import DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1,",
"roi = total_payouts / sum(bet_amts) res = -roi - (total_payouts / 5000) print(f'Score:",
"1 payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds",
"sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from trueskill import BETA, global_env, rate_1vs1,",
"or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] +",
"is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds cash += fw_odds * fight['bet']",
"= -fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds cash +=",
"bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt >= 1, f'bet",
"f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2],",
"# get winner fw = fight['winner']['fighter'] is_win_1 = fw == f1 fl =",
"= (actual[0] + is_actual_correct, actual[1] + 1) cash = -fight['bet'] if is_actual_correct: fw_odds",
"max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred:",
"r in team2) sum_sigma = sum(r.sigma ** 2 for r in chain(team1, team2))",
"= f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight}",
"y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params, train=0): logger.info('Starting main training') all_data",
"fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped?",
"ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds > 0: return us_odds / 100",
"correct, accuracy[1] + 1) # actual outcome pred_flipped = False if 'bet' in",
"= f1_pred fl_pred = f2_pred else: fw_pred = f2_pred fl_pred = f1_pred #",
"def to_decimal_odds(us_odds): if us_odds > 0: return us_odds / 100 + 1 else:",
"# trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma",
"+ 1 def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return 1",
"bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52 # -8.01",
"else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi =",
"-8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797",
"not es.stop(): solutions = es.ask() fitness = [main(x, train=1) for x in solutions]",
"f1_ts - f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma * 2 f1_ts_max",
"= sum([t for t in odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy",
"-62.62 if abs(sum(tab) - sheet) > 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug!",
"fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred = f1_pred fl_pred =",
"/ sum(bet_amts) res = -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi",
"random import numpy as np from cma import CMAEvolutionStrategy, CMAOptions from loguru import",
"13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62",
"log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw}",
"numpy as np from cma import CMAEvolutionStrategy, CMAOptions from loguru import logger from",
"f2_sigma * 2 # odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if",
"== f1 fl = f2 if is_win_1 else f1 if not is_win_1 and",
"flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction'] != f1) or ( f2_pred",
"f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1],",
"scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date = None ratings =",
"X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}')",
"bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt",
"bet_multis = [] bet_multis_cat = [] preds_flipped = [] odds_outcomes = [] #",
"not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg",
"accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy,",
"in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc",
"continue if is_win_1: fw_pred = f1_pred fl_pred = f2_pred else: fw_pred = f2_pred",
"y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg",
"f2_odds else: f_odds = 1 / f2_odds - 1 / f1_odds bet_odds_multi =",
"rate_1vs1, Rating from xgboost import XGBRegressor from .data import DATA from .data_2016 import",
"f_pred = f1_pred - f2_pred else: f_pred = f2_pred - f1_pred bet_pred_multi =",
"############################# # prediction made if 'prediction' in fight and fight['prediction'] is None: if",
"logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test)) reg",
"< f2_odds and is_win_1) or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2))",
"datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet",
"if not -50 < f1_odds < 50 or not -50 < f2_odds <",
"+ sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds",
"1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a =",
"= [] # loop through scenes for i, scene in enumerate(all_data): is_training =",
"multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in",
"{f2}') continue if is_win_1: fw_pred = f1_pred fl_pred = f2_pred else: fw_pred =",
"== len(bounds[0]) if train: sigma = 1 opts = CMAOptions() # opts['tolx'] =",
"+= bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred: f_ts_max = f1_ts_max",
"-8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544",
"bet_tma_b = -26.933801584409544 # init reg = None scaler = MinMaxScaler() cutoff =",
"else f1 if not is_win_1 and fw != f2 and fw is not",
"max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}')",
"ts = global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds > 0:",
"v in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]:",
"reg_params = { 'n_estimators': 100 if train else 1000, # 'learning_rate': 0.09426181829690375, #",
"res = -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}%",
"logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train = 0",
"else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def",
"+= [1] wins_losses[f2] += [-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl] =",
"rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training: if 'winner' in fight: X_train.extend(fight_data)",
"- sum(r.mu for r in team2) sum_sigma = sum(r.sigma ** 2 for r",
"reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names",
"-50 < f1_odds < 50 or not -50 < f2_odds < 50: raise",
"1 # skip if no odds: if 'odds' not in fight: continue f1",
"> 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) /",
"{scene[\"name\"]}') for fight in scene['fights']: bet_size = 1 # skip if no odds:",
"+= [-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] =",
"< cutoff if not is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') #",
"fw == f1 fl = f2 if is_win_1 else f1 if not is_win_1",
"is_win_1 else f2_odds cash += fw_odds * fight['bet'] else: fw_odds = f2_odds if",
"+= f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds > f1_odds",
"f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred",
"f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi =",
"= hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a",
"win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate =",
"early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda: 0.5) X_train = [] y_train =",
"l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def",
"/ max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma,",
"0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight':",
"is_win_1 and f2_pred > f1_pred: correct = 1 payout += f2_odds * bet_size",
"= 1 payout += f1_odds * bet_size elif not is_win_1 and f2_pred >",
"= 15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50",
"* (BETA * BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom)",
"'~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)}",
"-1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg = None scaler",
"if f1_pred > f2_pred: f_pred = f1_pred - f2_pred else: f_pred = f2_pred",
"reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max",
"CMAEvolutionStrategy, CMAOptions from loguru import logger from math import sqrt from sklearn.preprocessing import",
"odds: if 'odds' not in fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name']",
"random import random import numpy as np from cma import CMAEvolutionStrategy, CMAOptions from",
"loguru import logger from math import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers",
"bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg =",
"100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f}",
"(f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct,",
"ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma",
"[] odds_outcomes = [] # loop through scenes for i, scene in enumerate(all_data):",
"fight['prediction'] != f1) or ( f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]}",
"from .data import DATA from .data_2016 import DATA_2016 from .data_2017 import DATA_2017 from",
"bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b = hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52",
"f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma,",
"= [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b',",
"through scenes for i, scene in enumerate(all_data): is_training = i < cutoff if",
"f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for",
"fight in scene['fights']: bet_size = 1 # skip if no odds: if 'odds'",
"f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update data if",
"bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred: f_odds = 1 /",
"early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds, f1_odds, f2_ts,",
"fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing",
"DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu",
"= 0 payout = -bet_size if is_win_1 and f1_pred > f2_pred: correct =",
"# wins and losses if f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate",
"${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if",
"< f1_odds < 50 or not -50 < f2_odds < 50: raise ValueError(f'surely",
"bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt >= 1,",
"for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}')",
"- f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1],",
"= 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop():",
"# -16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338 #",
"0, 0, 0 ] bounds = [[-np.inf], [np.inf]] assert len(params) == len(names) #",
"* 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts)",
"mu if f1_pred > f2_pred: f_ts = f1_ts - f2_ts else: f_ts =",
"= [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min,",
"if not is_win_1 and fw != f2 and fw is not None: raise",
"bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt >=",
"bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins",
"# -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b =",
"else: return 100 / us_odds + 1 def to_implied_odds(us_odds: float) -> float: decimal_odds",
"bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 #",
"logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes if t > 0]) /",
"[ 0, 0, 0, 0, 0, 0 ] bounds = [[-np.inf], [np.inf]] assert",
"bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred: f_ts_min =",
"f2_pred and fight['prediction'] != f1) or ( f2_pred > f1_pred and fight['prediction'] !=",
"> f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max",
"f2_pred: f_ts = f1_ts - f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi",
"fight['odds'][f2] if not -50 < f1_odds < 50 or not -50 < f2_odds",
"ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training: if 'winner' in",
"+ DATA_2017 + DATA_2018 + DATA # estimators, learning_rate = hyper_params # gamma,",
"tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators,",
"scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']:",
"depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma',",
"= (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}')",
"= fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts =",
"= {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days",
"= np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}')",
"== len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v:",
"logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi = total_payouts /",
"= 1 opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds es",
"if is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds cash += fw_odds *",
"[] X_test = [] y_test = [] payouts = [] bet_amts = []",
"f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1],",
"your bets elif 'winner' not in fight: logger.warning(f'Pending {f1} vs {f2}') continue if",
"0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts)",
"f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet x{bet_multi}",
"* 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue",
"no odds: if 'odds' not in fight: continue f1 = fight['fighters'][0]['name'] f2 =",
"= ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min",
"DATA_2017 + DATA_2018 + DATA # estimators, learning_rate = hyper_params # gamma, max_depth,",
"bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi",
"def summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('')",
"not is_win_1 and f2_pred > f1_pred: correct = 1 payout += f2_odds *",
"[f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and",
"y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning",
"ratings[fl], drawn=drawn) ################################### # train if is_training: if 'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1,",
"f_pred = f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1,",
"max if f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max =",
"[[-np.inf], [np.inf]] assert len(params) == len(names) # assert len(params) == len(bounds[0]) if train:",
"- f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi",
"init reg = None scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date",
"bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a,",
"data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 < f1_odds <",
"bet_multi) assert bet_amt >= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) #############################",
"decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError: return 1 def",
"= fight['odds'][f2] if not -50 < f1_odds < 50 or not -50 <",
"else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred > f2_pred",
"Counter, defaultdict, OrderedDict from itertools import chain from random import random import numpy",
"last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## #",
"None: raise ValueError(f'unknown winner {fw}') drawn = fw is None # update wins",
"= [] bet_amts = [] accuracy = (0, 0) tab = [] tab_amts",
"f1_wnl_winrate, ] ] ########################################## # update data if 'winner' in fight: # get",
"f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max",
"len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}%",
"'last', '~last', 'early', '~early', 'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names)",
"############################# # bet scaling bet_multi = 1 # pred max if f1_pred >",
"-roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}')",
"actual outcome pred_flipped = False if 'bet' in fight: is_actual_correct = fight['prediction'] ==",
"decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\"",
"-bet_size if is_win_1 and f1_pred > f2_pred: correct = 1 payout += f1_odds",
"[main(x, train=1) for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('')",
"f2_odds and is_win_1) or (f2_odds > f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy",
"global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if us_odds > 0: return us_odds",
"= round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred",
"pred_flipped = False if 'bet' in fight: is_actual_correct = fight['prediction'] == fw actual",
"y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0)",
"and fight['prediction'] != f1) or ( f2_pred > f1_pred and fight['prediction'] != f2)",
"logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days",
"5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg,",
"fw_odds = f1_odds if is_win_1 else f2_odds cash += fw_odds * fight['bet'] else:",
"DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for r",
"int(round(2.1956102758009424)), # 2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, #",
"odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth)",
"/ us_odds + 1 def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try:",
"ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training: if 'winner'",
"sigma, inopts=opts) while not es.stop(): solutions = es.ask() fitness = [main(x, train=1) for",
"last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ##########################################",
"X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight",
"- f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi",
"f1_pred > f2_pred: f_pred = f1_pred - f2_pred else: f_pred = f2_pred -",
"f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}'",
"} # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089",
"- f1_ts_max, last_fights[f2], last_fights[f1], early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ]",
"0.6) start_date = None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights",
"= f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser",
"logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size = 1 # skip if",
"= f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0,",
"regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test),",
"2)) accuracy = (accuracy[0] + correct, accuracy[1] + 1) # actual outcome pred_flipped",
"is_actual_correct, actual[1] + 1) cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds if",
"not is_win_1 and fw != f2 and fw is not None: raise ValueError(f'unknown",
"f2_pred else: fw_pred = f2_pred fl_pred = f1_pred # add test data X_test.extend(scaled_fight_data)",
"'~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('')",
"= hyper_params bet_ts_a = -50.59979897765422 # -26.88 # -3.52 # -8.01 bet_ts_b =",
"> 0: return us_odds / 100 + 1 else: return 100 / us_odds",
"-50 < f2_odds < 50: raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}')",
"7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet ${tab.mean():.2f}') sheet =",
"f_ts_min = f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1,",
"{log_ratings}') if train: total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts) res =",
"DATA_2018 + DATA # estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight =",
"cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1 else f2_odds cash",
"f2_pred - f1_pred bet_pred_multi = np.polyval([bet_pred_a, bet_pred_b], [f_pred])[0] bet_pred_multi = round(min(1, max(0, bet_pred_multi)))",
"= [] preds_flipped = [] odds_outcomes = [] # loop through scenes for",
"eval_set.append((np.array(X_test), y_test)) reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc',",
"n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg def main(hyper_params,",
"defaultdict, OrderedDict from itertools import chain from random import random import numpy as",
"f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate",
"= np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes if t",
"= reg.evals_result() params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth:",
"= datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train,",
"bet_multis_cat = [] preds_flipped = [] odds_outcomes = [] # loop through scenes",
"to be considered as current best estimate of the optimum') print(list(es.result[5])) else: main(params)",
"tab_amts.append(fight['bet']) # pred flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction'] != f1)",
"in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite:",
"= [] actual = (0, 0) actual_debug = [] bet_multis = [] bet_multis_cat",
"float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError:",
"days:.2f} per bet ${tab.mean():.2f}') sheet = -62.62 if abs(sum(tab) - sheet) > 0.01:",
"logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%') feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff',",
"bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred > f2_pred:",
"], [ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts",
"last_fights[f1], last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob,",
"f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi",
"f2_ts + f2_sigma * 2 # odds data f1_odds = fight['odds'][f1] f2_odds =",
"wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses",
"bet_tma_a = -28.62283185173976 bet_tma_b = -26.933801584409544 # init reg = None scaler =",
"sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per day:",
"ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob =",
"last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ###################################",
"max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data =",
".data import DATA from .data_2016 import DATA_2016 from .data_2017 import DATA_2017 from .data_2018",
"ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl], drawn=drawn) ################################### # train if is_training: if",
"bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96 #",
"'bet_tma_a', 'bet_tma_b', ] params = [ 0, 0, 0, 0, 0, 0 ]",
"bet_odds_b, bet_wnl_a, bet_wnl_b = hyper_params bet_pred_a = 1.713980438805089 # -3.55 bet_pred_b = -4.065137791049565",
"params = reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy:",
"'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), #",
"k, v in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if",
"logger.info('') logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) *",
"= ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min =",
"f1_pred > f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate -",
"hyper_params # gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params",
"sheet:.2f}') def run(): train = 0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a',",
"else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, #",
"winner fw = fight['winner']['fighter'] is_win_1 = fw == f1 fl = f2 if",
"else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi",
"+= bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred: f_odds = 1",
"[f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi)",
"f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1,",
"else: fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred",
"= i < cutoff if not is_training: if not reg: start_date = datetime.strptime(scene['date'],",
"fight['bet'] else: fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) #",
"= win_probability([ratings[f2]], [ratings[f1]]) # wins losses data f1_wins_losses = Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1]",
"'odds' not in fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill",
"= f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser = f2_pred else: exp_winner",
"int(len(all_data) * 0.6) start_date = None ratings = defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda:",
"bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred: f_ts_min",
"BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom) def to_decimal_odds(us_odds): if",
"] ] ########################################## # update data if 'winner' in fight: # get winner",
"is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train =",
"+ f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma * 2 # odds",
"= round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred",
"= Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob,",
"accuracy[1] + 1) # actual outcome pred_flipped = False if 'bet' in fight:",
"= round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred",
"1 opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds es =",
"last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl] =",
"0 payout = -bet_size if is_win_1 and f1_pred > f2_pred: correct = 1",
"y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result() params = reg.get_params() logger.info(f'Num estimators:",
".data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for r in team1)",
"# trueskill max if f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max else:",
"try: return 1 / decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None,",
"f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min -",
"Rating from xgboost import XGBRegressor from .data import DATA from .data_2016 import DATA_2016",
"= [] payouts = [] bet_amts = [] accuracy = (0, 0) tab",
"[] y_train = [] X_test = [] y_test = [] payouts = []",
"= [] y_train = [] X_test = [] y_test = [] payouts =",
"np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') #",
"train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253,",
"f2 = fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts",
"i < cutoff if not is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d')",
"# odds data f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 <",
"**reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size = 1 # skip",
"= ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma",
"# testing outcome correct = 0 payout = -bet_size if is_win_1 and f1_pred",
"- f2_sigma * 2 f1_ts_max = f1_ts + f1_sigma * 2 f2_ts_max =",
"and f1_pred > f2_pred: correct = 1 payout += f1_odds * bet_size elif",
"] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:')",
"'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)}",
"in fight: # get winner fw = fight['winner']['fighter'] is_win_1 = fw == f1",
"{accuracy[0]}/{accuracy[1]} = {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}')",
"BETA, global_env, rate_1vs1, Rating from xgboost import XGBRegressor from .data import DATA from",
"not is_win_1]) # testing outcome correct = 0 payout = -bet_size if is_win_1",
"f2_pred: f_odds = 1 / f1_odds - 1 / f2_odds else: f_odds =",
"'~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg",
"[] preds_flipped = [] odds_outcomes = [] # loop through scenes for i,",
"\"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi}",
"assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features",
"f2_odds < 50: raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob =",
"last_fights[fw] = 1 last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw],",
"[] bet_amts = [] accuracy = (0, 0) tab = [] tab_amts =",
"last_fights = defaultdict(lambda: 0.5) X_train = [] y_train = [] X_test = []",
"f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi)))",
"print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space, to",
"import DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2):",
"50: raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]])",
"collections import Counter, defaultdict, OrderedDict from itertools import chain from random import random",
"Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual,",
"f2 and fw is not None: raise ValueError(f'unknown winner {fw}') drawn = fw",
"vs {len(reg.feature_importances_)} reg values' logger.info('') logger.info(f'Features:') features = SortedDict({v: k for k, v",
"(datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) / days:.2f} per bet",
"payout += f1_odds * bet_size elif not is_win_1 and f2_pred > f1_pred: correct",
"Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds,",
"trueskill mu if f1_pred > f2_pred: f_ts = f1_ts - f2_ts else: f_ts",
"= XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return reg",
"+ 1 else: return 100 / us_odds + 1 def to_implied_odds(us_odds: float) ->",
"1 / decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train, y_train, X_test=None, y_test=None, **reg_params):",
"MinMaxScaler from sortedcontainers import SortedDict from trueskill import BETA, global_env, rate_1vs1, Rating from",
"xgboost import XGBRegressor from .data import DATA from .data_2016 import DATA_2016 from .data_2017",
"np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') #",
"bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions = es.ask() fitness",
"-17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a =",
"actual[1] + 1) cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds if is_win_1",
"bet_size = 1 # skip if no odds: if 'odds' not in fight:",
"= sum(r.mu for r in team1) - sum(r.mu for r in team2) sum_sigma",
"# estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight = hyper_params # max_delta_step,",
"# 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, }",
"for t in odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]} =",
"= total_payouts / sum(bet_amts) res = -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f}",
"y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred =",
"start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}')",
"to_decimal_odds(us_odds): if us_odds > 0: return us_odds / 100 + 1 else: return",
"logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit ${sum(tab):.0f}') days = (datetime.now() - datetime(2019,",
"+ is_actual_correct, actual[1] + 1) cash = -fight['bet'] if is_actual_correct: fw_odds = f1_odds",
"f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max",
"= last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl] = 0 # update",
"- sheet:.2f}') def run(): train = 0 names = [ # 'bet_pred_a', 'bet_pred_b',",
"es.ask() fitness = [main(x, train=1) for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0]))",
"[] bet_multis = [] bet_multis_cat = [] preds_flipped = [] odds_outcomes = []",
"feature_names = [ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff',",
"bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b",
"= {accuracy[0]/accuracy[1]*100:.1f}% Odds: {odds_acc*100:.1f}%') logger.info(f'ROI {sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days",
"= f1 pred_exp_loser = f1_pred logger.warning(f'[{pred_exp_winner * 100:.0f}% vs {pred_exp_loser * 100:.0f}%] Bet",
"{f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]]) # wins losses",
"np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0] bet_tma_multi = round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size",
"f1_wnl_winrate bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi +=",
"'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ]",
"testing outcome correct = 0 payout = -bet_size if is_win_1 and f1_pred >",
"# trueskill min if f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min else:",
"is_win_1]) ################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) #############################",
"for x in solutions] es.tell(solutions, fitness) es.disp() print(list(es.result[0])) print(list(es.result[5])) es.result_pretty() print('') print('best') print(list(es.result[0]))",
"abs(sum(tab) - sheet) > 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} !=",
"'winner' in fight: # get winner fw = fight['winner']['fighter'] is_win_1 = fw ==",
"wins_losses[f2] += [-1] # update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw]",
"odds_outcomes = [] # loop through scenes for i, scene in enumerate(all_data): is_training",
"${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab = np.array(tab) logger.info('')",
"pred flipped? pred_flipped = (f1_pred > f2_pred and fight['prediction'] != f1) or (",
"# scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]}",
"+= bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred > f2_pred: f_wnl =",
"# prediction made if 'prediction' in fight and fight['prediction'] is None: if f1_pred",
"vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f}",
"import Counter, defaultdict, OrderedDict from itertools import chain from random import random import",
"if 'prediction' in fight and fight['prediction'] is None: if f1_pred > f2_pred: exp_winner",
"test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct = 0 payout",
"* 2 f2_ts_max = f2_ts + f2_sigma * 2 # odds data f1_odds",
"es.stop(): solutions = es.ask() fitness = [main(x, train=1) for x in solutions] es.tell(solutions,",
"- 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0,",
"= scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in",
"fl_pred = f2_pred else: fw_pred = f2_pred fl_pred = f1_pred # add test",
"f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [",
"f2_pred: correct = 1 payout += f1_odds * bet_size elif not is_win_1 and",
"/ 5000) print(f'Score: {-res*100:.2f} ROI {roi * 100:.1f}% Profit ${total_payouts:.0f}') return res else:",
"!= f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped",
"add test data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct = 0",
"(datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common",
"< 50 or not -50 < f2_odds < 50: raise ValueError(f'surely these odds",
"defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights = defaultdict(lambda:",
"pred_flipped = (f1_pred > f2_pred and fight['prediction'] != f1) or ( f2_pred >",
"else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser = f1 pred_exp_loser = f1_pred",
"\" \"}[{sum(payouts):.0f}|{payout:.0f}]' log_pred = f'[{fw_pred * 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight =",
"for r in chain(team1, team2)) size = len(team1) + len(team2) denom = sqrt(size",
"None # update wins losses wins_losses[f1] += [1] wins_losses[f2] += [-1] # update",
"payout += f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds >",
"################################### # test else: scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# #",
"{exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your",
"distribution mean in \"phenotype\" space, to be considered as current best estimate of",
"bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') # trueskill max if f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max",
"fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min -",
"def win_probability(team1, team2): delta_mu = sum(r.mu for r in team1) - sum(r.mu for",
"[ win2_prob, f2_odds, f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts -",
"> f2_pred: f_pred = f1_pred - f2_pred else: f_pred = f2_pred - f1_pred",
"= f2_wins_losses[1] / max(1, len(wins_losses[f2])) fight_data = [ [ win1_prob, f1_odds, f2_odds, f1_ts,",
"'wins', '~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features",
"r in team1) - sum(r.mu for r in team2) sum_sigma = sum(r.sigma **",
"if f1_pred > f2_pred: f_ts = f1_ts - f2_ts else: f_ts = f2_ts",
"scale scaler.partial_fit(X_train) X_train = scaler.transform(X_train) reg = get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}')",
"< 50: raise ValueError(f'surely these odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]],",
"1) # actual outcome pred_flipped = False if 'bet' in fight: is_actual_correct =",
"import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import SortedDict from trueskill import",
"es.result_pretty() print('') print('best') print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space, to be",
"# -3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b",
"bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi = round(min(1, max(0, bet_odds_multi))) bet_multi += bet_odds_multi",
"f2_odds * bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds > f1_odds and",
"= False if 'bet' in fight: is_actual_correct = fight['prediction'] == fw actual =",
"Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f}",
"] params = [ 0, 0, 0, 0, 0, 0 ] bounds =",
"is_win_1 = fw == f1 fl = f2 if is_win_1 else f1 if",
"(BETA * BETA) + sum_sigma) ts = global_env() return ts.cdf(delta_mu / denom) def",
"'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params",
"= defaultdict(lambda: Rating()) wins_losses = defaultdict(lambda: []) early_fights = defaultdict(lambda: 0.5) last_fights =",
"days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis: {Counter(bet_multis_cat).most_common()}') if actual[1]: tab",
"[f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min",
"-3.52 # -8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b,",
"payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes if",
"params = [ 0, 0, 0, 0, 0, 0 ] bounds = [[-np.inf],",
"- f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi",
"if is_win_1 else f1 if not is_win_1 and fw != f2 and fw",
"last_fights[f2], early_fights[f1], early_fights[f2], f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, ], [ win2_prob, f2_odds,",
"logger.info('') logger.info('Testing:') odds_acc = sum([t for t in odds_outcomes if t > 0])",
"- sheet) > 0.01: for l in actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f}",
"bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes): logger.info('') logger.info('Tree info:') # reg = get_regressor(X_train,",
"payouts = [] bet_amts = [] accuracy = (0, 0) tab = []",
"pred max if f1_pred > f2_pred: f_pred = f1_pred - f2_pred else: f_pred",
"logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if X_test and y_test: eval_set.append((np.array(X_test), y_test))",
"fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if",
"DATA from .data_2016 import DATA_2016 from .data_2017 import DATA_2017 from .data_2018 import DATA_2018",
"# -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b = 0.0837110561236318 # -16.17 bet_wnl_a",
"is_training = i < cutoff if not is_training: if not reg: start_date =",
"estimators, learning_rate = hyper_params # gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample,",
"sum([t for t in odds_outcomes if t > 0]) / len(odds_outcomes) logger.info(f'Accuracy {accuracy[0]}/{accuracy[1]}",
"'winner' in fight: X_train.extend(fight_data) y_train.extend([is_win_1, not is_win_1]) ################################### # test else: scaled_fight_data =",
"fw != f2 and fw is not None: raise ValueError(f'unknown winner {fw}') drawn",
"= bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions = es.ask()",
"'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a, bet_wnl_b",
"info:') # reg = get_regressor(X_train, y_train, X_test, y_test, estimators=estimators, max_depth=max_depth) reg_score = reg.evals_result()",
"f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min = f2_ts - f2_sigma *",
"= round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt =",
"-3.52 # -8.01 bet_ts_b = -69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a",
"/ f2_odds else: f_odds = 1 / f2_odds - 1 / f1_odds bet_odds_multi",
"OrderedDict from itertools import chain from random import random import numpy as np",
"'n_estimators': 100 if train else 1000, # 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma':",
"= np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}')",
"winner {fw}') drawn = fw is None # update wins losses wins_losses[f1] +=",
"chain(team1, team2)) size = len(team1) + len(team2) denom = sqrt(size * (BETA *",
"team2) sum_sigma = sum(r.sigma ** 2 for r in chain(team1, team2)) size =",
"Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1]",
"tab = [] tab_amts = [] actual = (0, 0) actual_debug = []",
"* bet_size odds_outcomes.append(int((f1_odds < f2_odds and is_win_1) or (f2_odds > f1_odds and not",
"MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date = None ratings = defaultdict(lambda: Rating())",
"reg = XGBRegressor(objective='reg:squarederror', n_jobs=4, **reg_params) reg = reg.fit(X_train, y_train, eval_set=eval_set, eval_metric='auc', verbose=0) return",
"= fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data f1_ts = ratings[f1].mu f1_sigma =",
"= hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators': 100",
"team2): delta_mu = sum(r.mu for r in team1) - sum(r.mu for r in",
"trueskill data f1_ts = ratings[f1].mu f1_sigma = ratings[f1].sigma f2_ts = ratings[f2].mu f2_sigma =",
"win_probability(team1, team2): delta_mu = sum(r.mu for r in team1) - sum(r.mu for r",
"{ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts = sum(payouts) roi = total_payouts",
"odds are wrong? {f1_odds} {f2_odds}') win1_prob = win_probability([ratings[f1]], [ratings[f2]]) win2_prob = win_probability([ratings[f2]], [ratings[f1]])",
"logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}% Profit",
"> f2_pred: f_wnl = f1_wnl_winrate - f2_wnl_winrate else: f_wnl = f2_wnl_winrate - f1_wnl_winrate",
"= f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped",
"+= bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size * bet_multi) assert bet_amt",
"f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0] bet_ts_multi = round(min(1, max(0, bet_ts_multi))) bet_multi +=",
"datetime from collections import Counter, defaultdict, OrderedDict from itertools import chain from random",
"f1_odds and not is_win_1))) payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1] +",
"to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your bets",
"def run(): train = 0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b',",
"= (accuracy[0] + correct, accuracy[1] + 1) # actual outcome pred_flipped = False",
"# -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963 bet_tma_a = -28.62283185173976",
"y_train, X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)]",
"logger.info('Actual:') logger.info(f'Accuracy {actual[0]}/{actual[1]} = {actual[0]/actual[1] * 100:.1f}%') logger.info(f'ROI {sum(tab) / sum(tab_amts) * 100:.2f}%",
"2.5506573766936533)), # 'min_child_weight': 3.5802932556001426, # 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404,",
"f2_ts_min - f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi)))",
"= f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate = f2_wins_losses[1] / max(1,",
"(f1_pred > f2_pred and fight['prediction'] != f1) or ( f2_pred > f1_pred and",
"'bet' in fight: is_actual_correct = fight['prediction'] == fw actual = (actual[0] + is_actual_correct,",
"= scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1",
"= reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi = 1 # pred max if",
"100:.1f}% Profit ${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat,",
"import logger from math import sqrt from sklearn.preprocessing import MinMaxScaler from sortedcontainers import",
"= [] X_test = [] y_test = [] payouts = [] bet_amts =",
"is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi))) ############################# # prediction made if 'prediction' in fight",
"( f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}')",
"-69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b = -1.128236337281963",
"max if f1_pred > f2_pred: f_pred = f1_pred - f2_pred else: f_pred =",
"logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size = 1 # skip if no",
"bet_wnl_multi = np.polyval([bet_wnl_a, bet_wnl_b], [f_wnl])[0] bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi",
"f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts - f2_ts, f1_ts_max -",
"{pred_exp_loser * 100:.0f}%] Bet x{bet_multi} on {exp_winner} to beat {exp_loser} [{ratings[exp_winner].mu:.0f} vs {ratings[exp_loser].mu:.0f}]')",
"= -69.5794588139756 # -72.60 # -3.52 # -8.01 bet_tmi_a = -45.94904856923797 bet_tmi_b =",
"[] y_test = [] payouts = [] bet_amts = [] accuracy = (0,",
"= 1 last_fights[fl] = 0 # update ratings ratings[fw], ratings[fl] = rate_1vs1(ratings[fw], ratings[fl],",
"[np.inf]] assert len(params) == len(names) # assert len(params) == len(bounds[0]) if train: sigma",
"- f2_ts else: f_ts = f2_ts - f1_ts bet_ts_multi = np.polyval([bet_ts_a, bet_ts_b], [f_ts])[0]",
"f1_ts_min bet_tmi_multi = np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi +=",
"actual_debug: logger.warning(l) logger.error(f'debug! {sheet:.2f} != {sum(tab):.2f} diff {sum(tab) - sheet:.2f}') def run(): train",
"-3.55 bet_pred_b = -4.065137791049565 # -17.93 bet_odds_a = 3.122323263774503 # -12.44 bet_odds_b =",
"${total_payouts:.0f}') return res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab,",
"features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc =",
"fw_odds * fight['bet'] else: fw_odds = f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2))",
"= es.ask() fitness = [main(x, train=1) for x in solutions] es.tell(solutions, fitness) es.disp()",
"= reg.get_params() logger.info(f'Num estimators: {params[\"n_estimators\"]}') logger.info(f'Learning rate: {params[\"learning_rate\"]:.2f}') logger.info(f'Max depth: {params[\"max_depth\"]}') logger.info(f'Accuracy: training={reg_score[\"validation_0\"][\"auc\"][-1]*100:.0f}%')",
"import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for r in team1) -",
"round(min(1, max(0, bet_tma_multi))) bet_multi += bet_tma_multi bet_multis_cat.append(f'tma:{bet_tma_multi:.0f}') bet_size *= round(bet_multi) bet_amt = round(bet_size",
"DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for r in team1) - sum(r.mu",
"{sum(tab) - sheet:.2f}') def run(): train = 0 names = [ # 'bet_pred_a',",
"bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if f1_pred > f2_pred: f_odds = 1 / f1_odds",
"-28.62283185173976 bet_tma_b = -26.933801584409544 # init reg = None scaler = MinMaxScaler() cutoff",
"{fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings = f'[{ratings[fw].mu:.0f} vs",
"bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes) def summary(reg, accuracy, payouts, start_date, bet_amts,",
"early_fights[f2], early_fights[f1], f2_wins_losses[1], f2_wins_losses[-1], f2_wnl_winrate, f1_wins_losses[1], f1_wins_losses[-1], f1_wnl_winrate, ] ] ########################################## # update",
"f1_pred fl_pred = f2_pred else: fw_pred = f2_pred fl_pred = f1_pred # add",
"not is_training: if not reg: start_date = datetime.strptime(scene['date'], '%Y-%m-%d') # scale scaler.partial_fit(X_train) X_train",
"good luck with your bets elif 'winner' not in fight: logger.warning(f'Pending {f1} vs",
"ratings[f2].mu f2_sigma = ratings[f2].sigma f1_ts_min = f1_ts - f1_sigma * 2 f2_ts_min =",
"sum(r.sigma ** 2 for r in chain(team1, team2)) size = len(team1) + len(team2)",
"in fight: logger.warning(f'Pending {f1} vs {f2}') continue if is_win_1: fw_pred = f1_pred fl_pred",
"zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts =",
"100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit: per day: ${sum(payouts) /",
"r in chain(team1, team2)) size = len(team1) + len(team2) denom = sqrt(size *",
"1 / f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b], [f_odds])[0] bet_odds_multi",
"data X_test.extend(scaled_fight_data) y_test.extend([is_win_1, not is_win_1]) # testing outcome correct = 0 payout =",
"f1_sigma * 2 f2_ts_max = f2_ts + f2_sigma * 2 # odds data",
"return us_odds / 100 + 1 else: return 100 / us_odds + 1",
"log_ratings = f'[{ratings[fw].mu:.0f} vs {ratings[fl].mu:.0f}]' logger.info(f'{log_balance} {log_pred} {log_fight} {log_ratings}') if train: total_payouts =",
"= CMAEvolutionStrategy(params, sigma, inopts=opts) while not es.stop(): solutions = es.ask() fitness = [main(x,",
"raise ValueError(f'unknown winner {fw}') drawn = fw is None # update wins losses",
"f1_odds, f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max -",
"# 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b, bet_odds_a, bet_odds_b, bet_wnl_a,",
"-10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a, bet_tmi_b, bet_tma_a, bet_tma_b =",
"0, 0, 0, 0, 0, 0 ] bounds = [[-np.inf], [np.inf]] assert len(params)",
"${sum(tab):.0f}') days = (datetime.now() - datetime(2019, 7, 13)).days logger.info(f'Profit: per day: ${sum(tab) /",
"'~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last', 'early', '~early', 'wins', '~wins', 'losses',",
"** 2 for r in chain(team1, team2)) size = len(team1) + len(team2) denom",
"= f2 pred_exp_loser = f2_pred else: exp_winner = f2 pred_exp_winner = f2_pred exp_loser",
"and fight['prediction'] is None: if f1_pred > f2_pred: exp_winner = f1 pred_exp_winner =",
"1 / f2_odds else: f_odds = 1 / f2_odds - 1 / f1_odds",
"per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis: {Counter(bet_multis).most_common(4)}') logger.info(f'cat multis:",
"X_test=None, y_test=None, **reg_params): \"\"\"get regressor\"\"\" logger.info('') logger.info('Training model...') eval_set = [(np.array(X_train), y_train)] if",
"vs {ratings[exp_loser].mu:.0f}]') continue # good luck with your bets elif 'winner' not in",
"= 0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b =",
"f1) or ( f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}: {cash:.2f}",
"continue # good luck with your bets elif 'winner' not in fight: logger.warning(f'Pending",
"= to_decimal_odds(us_odds) try: return 1 / decimal_odds except ZeroDivisionError: return 1 def get_regressor(X_train,",
"in zip(feature_names, reg.feature_importances_)}) for k in features.keys(): logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts",
"size = len(team1) + len(team2) denom = sqrt(size * (BETA * BETA) +",
"= [] y_test = [] payouts = [] bet_amts = [] accuracy =",
"bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred: f_ts_min = f1_ts_min -",
"+ len(team2) denom = sqrt(size * (BETA * BETA) + sum_sigma) ts =",
"train: total_payouts = sum(payouts) roi = total_payouts / sum(bet_amts) res = -roi -",
"# -8.01 bet_wnl_b = -10.111913271763338 # -4.96 # 2.50 # bet_ts_a, bet_ts_b, bet_tmi_a,",
"100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings =",
"min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight = hyper_params reg_params = { 'n_estimators':",
"'~wins', 'losses', '~losses', 'winrate', '~winrate', ] assert len(feature_names) == len(reg.feature_importances_), f'{len(feature_names)} features vs",
"if 'odds' not in fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] #",
"from xgboost import XGBRegressor from .data import DATA from .data_2016 import DATA_2016 from",
"- start_date).days logger.info(f'Profit: per day: ${sum(payouts) / days:.2f} per bet ${payouts.mean():.2f}') logger.info(f'Common multis:",
"= round(bet_size * bet_multi) assert bet_amt >= 1, f'bet multi is fucked: {bet_multi}'",
"scaled_fight_data = scaler.transform(fight_data) f1_pred, f2_pred = reg.predict(scaled_fight_data) ############################# # bet scaling bet_multi =",
"= Counter(wins_losses[f1]) f1_wnl_winrate = f1_wins_losses[1] / max(1, len(wins_losses[f1])) f2_wins_losses = Counter(wins_losses[f2]) f2_wnl_winrate =",
"{fw_odds:.2f}: {cash:.2f} {fight[\"prediction\"]} {fight[\"date\"]}') preds_flipped.append(int(pred_flipped)) log_balance = f'{\"!!\" if pred_flipped else \" \"}[{sum(payouts):.0f}|{payout:.0f}]'",
"(accuracy[0] + correct, accuracy[1] + 1) # actual outcome pred_flipped = False if",
"None scaler = MinMaxScaler() cutoff = int(len(all_data) * 0.6) start_date = None ratings",
"payouts.append(round(payout, 2)) accuracy = (accuracy[0] + correct, accuracy[1] + 1) # actual outcome",
"* 100:.0f}% vs {fl_pred * 100:.0f}%]' log_fight = f'x{bet_multi} {fw} {fight[\"winner\"][\"by\"]} {fl}' log_ratings",
"CMAOptions from loguru import logger from math import sqrt from sklearn.preprocessing import MinMaxScaler",
"get_regressor(X_train, y_train, **reg_params) logger.info('') logger.info(f'{scene[\"date\"]} {scene[\"name\"]}') for fight in scene['fights']: bet_size = 1",
"logger.info(f'{features[k]}: {k*1000:.0f}') continue if accuracy[1]: payouts = np.array(payouts) logger.info('') logger.info('Testing:') odds_acc = sum([t",
"f1_pred > f2_pred: f_odds = 1 / f1_odds - 1 / f2_odds else:",
"f1_pred > f2_pred: correct = 1 payout += f1_odds * bet_size elif not",
"/ 100 + 1 else: return 100 / us_odds + 1 def to_implied_odds(us_odds:",
"1 def to_implied_odds(us_odds: float) -> float: decimal_odds = to_decimal_odds(us_odds) try: return 1 /",
"'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a', 'bet_tma_b', ] params = [ 0,",
"for fight in scene['fights']: bet_size = 1 # skip if no odds: if",
"np.polyval([bet_tmi_a, bet_tmi_b], [f_ts_min])[0] bet_tmi_multi = round(min(1, max(0, bet_tmi_multi))) bet_multi += bet_tmi_multi bet_multis_cat.append(f'tmi:{bet_tmi_multi:.0f}') #",
"# 'learning_rate': 0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)),",
"skip if no odds: if 'odds' not in fight: continue f1 = fight['fighters'][0]['name']",
"= 0 names = [ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a',",
"bet_pred_multi = round(min(1, max(0, bet_pred_multi))) bet_multi += bet_pred_multi bet_multis_cat.append(f'pred:{bet_pred_multi:.0f}') # odds diff if",
"= hyper_params # gamma, max_depth, min_child_weight = hyper_params # max_delta_step, subsample, scale_pos_weight =",
"[ # 'bet_pred_a', 'bet_pred_b', 'bet_odds_a', 'bet_odds_b', 'bet_wnl_a', 'bet_wnl_b', 'bet_ts_a', 'bet_ts_b', 'bet_tmi_a', 'bet_tmi_b', 'bet_tma_a',",
"f1_pred > f2_pred: f_ts = f1_ts - f2_ts else: f_ts = f2_ts -",
"import DATA_2017 from .data_2018 import DATA_2018 def win_probability(team1, team2): delta_mu = sum(r.mu for",
"CMAOptions() # opts['tolx'] = 1E-2 opts['bounds'] = bounds es = CMAEvolutionStrategy(params, sigma, inopts=opts)",
"0.09426181829690375, # 0.24678854038938264 # 'gamma': 0.1860088097748791, # 0.0012826703538762253, # 'max_depth': int(round(2.1956102758009424)), # 2.5506573766936533)),",
"fight: # get winner fw = fight['winner']['fighter'] is_win_1 = fw == f1 fl",
"us_odds > 0: return us_odds / 100 + 1 else: return 100 /",
"not in fight: continue f1 = fight['fighters'][0]['name'] f2 = fight['fighters'][1]['name'] # trueskill data",
"return reg def main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016 + DATA_2017",
"i, scene in enumerate(all_data): is_training = i < cutoff if not is_training: if",
"0.0837110561236318 # -16.17 bet_wnl_a = 15.100288654913749 # -3.52 # -8.01 bet_wnl_b = -10.111913271763338",
"> f2_pred: exp_winner = f1 pred_exp_winner = f1_pred exp_loser = f2 pred_exp_loser =",
"total_payouts / sum(bet_amts) res = -roi - (total_payouts / 5000) print(f'Score: {-res*100:.2f} ROI",
"if f1_pred > f2_pred: f_ts_min = f1_ts_min - f2_ts_min else: f_ts_min = f2_ts_min",
"# 'max_delta_step': 0.10779250505931337, # 'subsample': 0.9859889452465481, # 'scale_pos_weight': 1.2283288967549404, } # bet_pred_a, bet_pred_b,",
"main(hyper_params, train=0): logger.info('Starting main training') all_data = DATA_2016 + DATA_2017 + DATA_2018 +",
"> f2_pred: f_ts = f1_ts - f2_ts else: f_ts = f2_ts - f1_ts",
"- f2_ts_max else: f_ts_max = f2_ts_max - f1_ts_max bet_tma_multi = np.polyval([bet_tma_a, bet_tma_b], [f_ts_max])[0]",
"f2_odds cash += fw_odds * fight['bet'] else: fw_odds = f2_odds if is_win_1 else",
"0 ] bounds = [[-np.inf], [np.inf]] assert len(params) == len(names) # assert len(params)",
"# update fights early_fights[fw] = last_fights[fw] early_fights[fl] = last_fights[fl] last_fights[fw] = 1 last_fights[fl]",
"f_odds = 1 / f2_odds - 1 / f1_odds bet_odds_multi = np.polyval([bet_odds_a, bet_odds_b],",
"max(0, bet_odds_multi))) bet_multi += bet_odds_multi bet_multis_cat.append(f'odds:{bet_odds_multi:.0f}') # wins and losses if f1_pred >",
"else f2_odds cash += fw_odds * fight['bet'] else: fw_odds = f2_odds if is_win_1",
"res else: summary(reg, accuracy, payouts, start_date, bet_amts, bet_multis, bet_multis_cat, actual, tab, tab_amts, odds_outcomes)",
"print(list(es.result[0])) print('') print('xfavorite: distribution mean in \"phenotype\" space, to be considered as current",
"f1_odds = fight['odds'][f1] f2_odds = fight['odds'][f2] if not -50 < f1_odds < 50",
"* bet_multi) assert bet_amt >= 1, f'bet multi is fucked: {bet_multi}' bet_amts.append(bet_size) bet_multis.append(int(round(bet_multi)))",
"{sum(payouts) / sum(bet_amts) * 100:.1f}% Profit ${sum(payouts):.0f}') days = (datetime.now() - start_date).days logger.info(f'Profit:",
"[] tab_amts = [] actual = (0, 0) actual_debug = [] bet_multis =",
"not -50 < f1_odds < 50 or not -50 < f2_odds < 50:",
"bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if f1_pred > f2_pred: f_ts =",
"trueskill max if f1_pred > f2_pred: f_ts_max = f1_ts_max - f2_ts_max else: f_ts_max",
"preds_flipped = [] odds_outcomes = [] # loop through scenes for i, scene",
"!= f1) or ( f2_pred > f1_pred and fight['prediction'] != f2) actual_debug.append(f'${fight[\"bet\"]} {fw_odds:.2f}:",
"if train: sigma = 1 opts = CMAOptions() # opts['tolx'] = 1E-2 opts['bounds']",
"y_test.extend([is_win_1, not is_win_1]) # testing outcome correct = 0 payout = -bet_size if",
"f2_odds if is_win_1 else f1_odds tab.append(round(cash, 2)) tab_amts.append(fight['bet']) # pred flipped? pred_flipped =",
"max(0, bet_ts_multi))) bet_multi += bet_ts_multi bet_multis_cat.append(f'ts:{bet_ts_multi:.0f}') # trueskill min if f1_pred > f2_pred:",
"f2_ts, f1_ts, f2_sigma, f1_sigma, f2_ts_min - f1_ts_min, f2_ts - f1_ts, f2_ts_max - f1_ts_max,",
"[ 'win%', 'odds', '~odds', 'ts', '~ts', 'sigma', '~sigma', 'ts_min_diff', 'ts_diff', 'ts_max_diff', 'last', '~last',",
"len(params) == len(bounds[0]) if train: sigma = 1 opts = CMAOptions() # opts['tolx']",
"bet_wnl_multi = round(min(1, max(0, bet_wnl_multi))) bet_multi += bet_wnl_multi bet_multis_cat.append(f'wnl:{bet_wnl_multi:.0f}') # trueskill mu if",
"[ [ win1_prob, f1_odds, f2_odds, f1_ts, f2_ts, f1_sigma, f2_sigma, f1_ts_min - f2_ts_min, f1_ts"
] |
[
"app = Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context():",
"app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic ) if __name__ ==",
"from flask_script import Manager from kron import Kron, db, restore_from_file from kron import",
"import Kron, db, restore_from_file from kron import Tag, Post, Archive, Box, Document, Person,",
"from kron import Kron, db, restore_from_file from kron import Tag, Post, Archive, Box,",
"db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic ) if __name__ == \"__main__\":",
"kron import Kron, db, restore_from_file from kron import Tag, Post, Archive, Box, Document,",
"Topic app = Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def",
"Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag,",
"from kron import Tag, Post, Archive, Box, Document, Person, Topic app = Kron(__name__)",
"return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic ) if",
"manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app,",
"Kron, db, restore_from_file from kron import Tag, Post, Archive, Box, Document, Person, Topic",
"Manager from kron import Kron, db, restore_from_file from kron import Tag, Post, Archive,",
"db, restore_from_file from kron import Tag, Post, Archive, Box, Document, Person, Topic app",
"import Tag, Post, Archive, Box, Document, Person, Topic app = Kron(__name__) manager =",
"Tag, Post, Archive, Box, Document, Person, Topic app = Kron(__name__) manager = Manager(app)",
"Archive, Box, Document, Person, Topic app = Kron(__name__) manager = Manager(app) @manager.command def",
"Person, Topic app = Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell",
"dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic ) if __name__",
"restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document,",
"Box, Document, Person, Topic app = Kron(__name__) manager = Manager(app) @manager.command def restore(file):",
"_make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic )",
"flask_script import Manager from kron import Kron, db, restore_from_file from kron import Tag,",
"Post, Archive, Box, Document, Person, Topic app = Kron(__name__) manager = Manager(app) @manager.command",
"= Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return",
"Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict(",
"@manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post,",
"kron import Tag, Post, Archive, Box, Document, Person, Topic app = Kron(__name__) manager",
"Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic ) if __name__ == \"__main__\": manager.run()",
"import Manager from kron import Kron, db, restore_from_file from kron import Tag, Post,",
"Document, Person, Topic app = Kron(__name__) manager = Manager(app) @manager.command def restore(file): restore_from_file(file)",
"def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive,",
"@manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person,",
"def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box, Document=Document, Person=Person, Topic=Topic",
"restore_from_file from kron import Tag, Post, Archive, Box, Document, Person, Topic app =",
"restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db, Tag=Tag, Post=Post, Archive=Archive, Box=Box,",
"= Manager(app) @manager.command def restore(file): restore_from_file(file) @manager.shell def _make_shell_context(): return dict( app=app, db=db,"
] |
[
"bulunmakta fakat sitedeki her link işimize yaramıyor # bu yüzden öncelikle göslem yapmanız",
"kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması için çokca otobüsü. ve",
"otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması için çokca otobüsü.",
"counter2=counter2+1 print(counter) list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt',",
"bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p))",
"linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması önemli # burda linkleri alıp",
"da size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri",
"kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin",
"link işimize yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle",
"and counter2==1: counter2=counter2+1 print(counter) list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam))",
"düzenlemeniz için korpus düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir",
"noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini",
"işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0",
"olduğunu keşfettim # bu yüzden buna uygun bir kod ile linkeri aldım #",
"türlü modelinizin bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi",
"size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması",
"r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\")",
"import requests from bs4 import BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde",
"in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8') for d in range(len(linklertoplam)): dosya.write('https://www.hurriyet.com.tr'+str(linklertoplam[d])+'\\n')",
"uygun bir kod ile linkeri aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme",
"Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması için",
"buna uygun bir kod ile linkeri aldım # oluşan korpusunu düzenlemeniz için korpus",
"if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter for i in range(list_min,list_max-1):",
"yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim",
"str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max =",
"gerekir bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49):",
"metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü.",
"if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max",
"counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter)",
"#https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden buna uygun bir",
"işimize yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte",
"yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri",
"page şeklinde olması önemli # burda linkleri alıp link listesi oluşturuyoruz #html bilenler",
"Fenerbahçe takım otobüsü olarak dönderecek bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak",
"bir kod ile linkeri aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme py",
"list_min=0 list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if",
"haber sitesinin page şeklinde olması önemli # burda linkleri alıp link listesi oluşturuyoruz",
"alıp link listesi oluşturuyoruz #html bilenler bilir a href kısmında bizim linklerimiz bulunmakta",
"in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if",
"#html bilenler bilir a href kısmında bizim linklerimiz bulunmakta fakat sitedeki her link",
"göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p=",
"link listesi oluşturuyoruz #html bilenler bilir a href kısmında bizim linklerimiz bulunmakta fakat",
"kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde",
"burda linkleri alıp link listesi oluşturuyoruz #html bilenler bilir a href kısmında bizim",
"in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in",
"for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8') for d in",
"linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor # bu yüzden öncelikle göslem",
"linkleri arasında olduğunu keşfettim # bu yüzden buna uygun bir kod ile linkeri",
"geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında",
"yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize",
"counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8') for d",
"gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu",
"diğer türlü modelinizin bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca",
"# Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu da",
"for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min =",
"otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler ve noktalama",
"bilenler bilir a href kısmında bizim linklerimiz bulunmakta fakat sitedeki her link işimize",
"oluşan korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini",
"önemli # burda linkleri alıp link listesi oluşturuyoruz #html bilenler bilir a href",
"print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter",
"bir program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım",
"takım otobüsü olarak dönderecek bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak #",
"str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter)",
"takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu da size Fenerbahçe",
"ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0",
"a href kısmında bizim linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor #",
"kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1",
"linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden buna uygun",
"bu yüzden buna uygun bir kod ile linkeri aldım # oluşan korpusunu düzenlemeniz",
"# oluşan korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum bu metninizdeki noktalama",
"size Fenerbahçe takım otobüsü olarak dönderecek bu da size Fenerbahçe ve otobüsü kelimesini",
"olarak dönderecek bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü",
"linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1:",
"bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler",
"ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu",
"href kısmında bizim linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor # bu",
"link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter",
"list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter for",
"aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum bu metninizdeki",
"birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu",
"otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu da size Fenerbahçe ve",
"işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden",
"her link işimize yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım",
"p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link",
"soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s)",
"gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim #",
"bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu",
"de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse #",
"bs4 import BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması önemli #",
"keşfettim # bu yüzden buna uygun bir kod ile linkeri aldım # oluşan",
"requests from bs4 import BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması",
"BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması önemli # burda linkleri",
"bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu",
"dönderecek bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin",
"bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin takım",
"Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz",
"for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for",
"otobüsü olarak dönderecek bu da size Fenerbahçe ve otobüsü kelimesini kazandıracak # diğer",
"from bs4 import BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması önemli",
"korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak",
"ve otobüsü kelimesini kazandıracak # diğer türlü modelinizin bu kelimeleri tanıması için çokca",
"oluşturuyoruz #html bilenler bilir a href kısmında bizim linklerimiz bulunmakta fakat sitedeki her",
"ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler ve noktalama işaretlerinden",
"işaretlerini kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size",
"kısmında bizim linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor # bu yüzden",
"yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr",
"tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel",
"noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0",
"bizim linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor # bu yüzden öncelikle",
"sitesinin page şeklinde olması önemli # burda linkleri alıp link listesi oluşturuyoruz #html",
"s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and",
"olması önemli # burda linkleri alıp link listesi oluşturuyoruz #html bilenler bilir a",
"list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\":",
"kod ile linkeri aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme py de",
"kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for",
"vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek",
"# burda linkleri alıp link listesi oluşturuyoruz #html bilenler bilir a href kısmında",
"cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu da size Fenerbahçe ve otobüsü",
"modelinizin bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir",
"yüzden buna uygun bir kod ile linkeri aldım # oluşan korpusunu düzenlemeniz için",
"py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse",
"= counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter for i",
"şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content)",
"yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr && /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden buna",
"counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter for i in",
"# bu yüzden buna uygun bir kod ile linkeri aldım # oluşan korpusunu",
"çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler ve",
"program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü",
"/seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden buna uygun bir kod ile",
"öncelikle haber sitesinin page şeklinde olması önemli # burda linkleri alıp link listesi",
"korpus düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek",
"özel isimler ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\")",
"linkeri aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum bu",
"listesi oluşturuyoruz #html bilenler bilir a href kısmında bizim linklerimiz bulunmakta fakat sitedeki",
"# bu yüzden öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan",
"ile linkeri aldım # oluşan korpusunu düzenlemeniz için korpus düzenleme py de bırakıyorum",
"çokca geçmesi gerekir bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for p",
"= counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8') for",
"linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p='",
"counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min = counter if str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1",
"counter2==1: counter2=counter2+1 print(counter) list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya=",
"range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in linkler:",
"i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8') for d in range(len(linklertoplam)):",
"arasında olduğunu keşfettim # bu yüzden buna uygun bir kod ile linkeri aldım",
"düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek",
"öncelikle göslem yapmanız geriyor ben yaptığım gözlemle birlikte işimize yarayan linkler #https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr &&",
"isimler ve noktalama işaretlerinden kurtuluyoruz for p in range(2,49): r=requests.get(\"https://www.hurriyet.com.tr/seyahat/konu/gezgin/\".format(p)) soup=BeautifulSoup(r.content) linkler=soup.find_all(\"a\") linklist=[]",
"bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin",
"counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s) if str_s[:]==\"https://play.google.com/store/apps/details?id=hurriyet.mobil.android&hl=tr\": print(counter) list_min",
"list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a', encoding='utf8')",
"örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak",
"fakat sitedeki her link işimize yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor",
"bilir a href kısmında bizim linklerimiz bulunmakta fakat sitedeki her link işimize yaramıyor",
"Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe takım otobüsü olarak dönderecek bu da size",
"şeklinde olması önemli # burda linkleri alıp link listesi oluşturuyoruz #html bilenler bilir",
"print(counter) list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i]) print(len(linklertoplam)) dosya= open('turklink.txt', 'a',",
"str_s[0:24]=='/seyahat/konu/gezgin/?p=' and counter2==1: counter2=counter2+1 print(counter) list_max = counter for i in range(list_min,list_max-1): linklertoplam.append(linklist[i])",
"# öncelikle haber sitesinin page şeklinde olması önemli # burda linkleri alıp link",
"sitedeki her link işimize yaramıyor # bu yüzden öncelikle göslem yapmanız geriyor ben",
"geçmesi gerekir bu şekilde özel isimler ve noktalama işaretlerinden kurtuluyoruz for p in",
"# diğer türlü modelinizin bu kelimeleri tanıması için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin",
"linkler=soup.find_all(\"a\") linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1",
"import BeautifulSoup linklertoplam=[] # öncelikle haber sitesinin page şeklinde olması önemli # burda",
"için korpus düzenleme py de bırakıyorum bu metninizdeki noktalama işaretlerini kaldıracak bir program",
"linkleri alıp link listesi oluşturuyoruz #html bilenler bilir a href kısmında bizim linklerimiz",
"kaldıracak bir program örnek vermek gerekirse # Fenerbahçe'nin takım otobüsü. cümlesini size Fenerbahçe",
"için çokca otobüsü. ve Fenerbahçe'nin kelimelerinin çokca geçmesi gerekir bu şekilde özel isimler",
"&& /seyahat/konu/gezgin/?p= linkleri arasında olduğunu keşfettim # bu yüzden buna uygun bir kod",
"linklist=[] list_min=0 list_max=0 counter=0 counter2=1 for link in linkler: s=link.get(\"href\") linklist.append(s) counter=counter+1 str_s=str(s)"
] |
[
"\"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict())",
"model_to.state_dict() for k in wt.keys() : if (not k in wf) | (k",
"(k == 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的 就是参数维度不匹配啦。 wf[k] = wt[k]",
"= copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys() : if (not k",
"copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys() : if (not k in",
"复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict()",
"in wt.keys() : if (not k in wf) | (k == 'fc.weight') |",
":return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys() :",
"| (k == 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的 就是参数维度不匹配啦。 wf[k] =",
"== 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的 就是参数维度不匹配啦。 wf[k] = wt[k] model_to.load_state_dict(wf)",
"= model_to.state_dict() for k in wt.keys() : if (not k in wf) |",
"wf) | (k == 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的 就是参数维度不匹配啦。 wf[k]",
"\"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys() : if",
"model_to): \"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf =",
"copy def transfer_weights(model_from, model_to): \"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return:",
"transfer_weights(model_from, model_to): \"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf",
"model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k",
"(not k in wf) | (k == 'fc.weight') | (k == 'fc.bias'): #",
"for k in wt.keys() : if (not k in wf) | (k ==",
"wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys() : if (not",
"def transfer_weights(model_from, model_to): \"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\"",
"wt.keys() : if (not k in wf) | (k == 'fc.weight') | (k",
"if (not k in wf) | (k == 'fc.weight') | (k == 'fc.bias'):",
":param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in",
"import copy def transfer_weights(model_from, model_to): \"\"\" 实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to:",
"to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt =",
"实现了从model_from到model to的相同网络参数的拷贝。 复制一个目标参数,把没有的都填上,就可以使用了, :param model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt",
"k in wf) | (k == 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的",
"model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for k in wt.keys()",
"wt = model_to.state_dict() for k in wt.keys() : if (not k in wf)",
": if (not k in wf) | (k == 'fc.weight') | (k ==",
":param model_from: :param model_to: :return: \"\"\" wf = copy.deepcopy(model_from.state_dict()) wt = model_to.state_dict() for",
"k in wt.keys() : if (not k in wf) | (k == 'fc.weight')",
"in wf) | (k == 'fc.weight') | (k == 'fc.bias'): # 例如两个都有fc层,那么要求fc层的参数是一样的 就是参数维度不匹配啦。"
] |
[
"'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate",
"end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query = query, start = i,",
"sort_by = 'submittedDate', sort_order = 'descending', max_results = max_results) new_papers = 0 for",
"= 'descending', max_results = max_results) new_papers = 0 for paper in result: arxiv_id",
"id files = os.listdir(tmp_list_path) for fname in files: if fname == '.DS_Store': continue",
"== '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not",
"= '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path)",
"'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE',",
"for i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers",
"'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list =",
"i += max_results time.sleep(3) print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w')",
"ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary",
"if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) #",
"domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID])",
"source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue",
"target_abs = papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue tmp = {",
"outs = {} year = latest_year i = 0 while year > end_year:",
"+= max_results time.sleep(3) print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as",
"end_year=2010, max_results=1000): outs = {} year = latest_year i = 0 while year",
"'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE',",
"'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC',",
"for paper in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in",
"'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR',",
"indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for",
"= papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue tmp",
"json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path =",
"in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if",
"cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL',",
"'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM',",
"# get raw paper id list (paper version >= 2) cates = ['econ.EM',",
"cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates +=",
"['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST',",
"= paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id and N > 1:",
"paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id and N > 1: arxiv_id",
"continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f)",
"= os.listdir(tmp_list_path) for fname in files: if fname == '.DS_Store': continue domain =",
"'.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list =",
"time import json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs =",
"{ \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3)",
"in files: if fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}',",
"time.sleep(3) print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs,",
"print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f) outs = generate_json_file(preprint_list, tmp_file_path,",
"max_results) new_papers = 0 for paper in result: arxiv_id = paper.id.split('/')[-1] N =",
"preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs",
"domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f) outs",
"if '.' in arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id)",
"as json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json',",
"list (paper version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP',",
"1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if",
"= arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if arxiv_id not",
"os.mkdir(tmp_file_path) # get raw paper id list (paper version >= 2) cates =",
"'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT',",
"domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by paper id files =",
"'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI',",
"'../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not",
"range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2],",
"'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI',",
"target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path =",
"max_ver = max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2",
"'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY',",
"= max_results) new_papers = 0 for paper in result: arxiv_id = paper.id.split('/')[-1] N",
"i = 0 while year > end_year: print(f\"Results {i} - {i+max_results}:\") result =",
"'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC',",
"\"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n')",
"0 for paper in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.'",
"['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC',",
"arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3)",
"max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}'",
"= arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail",
"'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS',",
"paper in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id",
"0 while year > end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query =",
"= query, start = i, sort_by = 'submittedDate', sort_order = 'descending', max_results =",
"= int(arxiv_id[-1]) if '.' in arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}',",
"'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG',",
"- {i+max_results}:\") result = arxiv.query(query = query, start = i, sort_by = 'submittedDate',",
"in arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers +=",
"cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR',",
"raw paper id list (paper version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH']",
"ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary",
"+= 1 year = int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] = [N]",
"outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers ==",
"'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900,",
"not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list (paper version >= 2)",
"{i+max_results}:\") result = arxiv.query(query = query, start = i, sort_by = 'submittedDate', sort_order",
"arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail to",
"not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year)",
"files = os.listdir(tmp_list_path) for fname in files: if fname == '.DS_Store': continue domain",
"import os import time import json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010,",
"year = latest_year i = 0 while year > end_year: print(f\"Results {i} -",
">= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF',",
"to get paper {ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\":",
"sort_order = 'descending', max_results = max_results) new_papers = 0 for paper in result:",
"preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}'",
"files: if fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r')",
"i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers =",
"'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD',",
"for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract",
"max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2)",
"paper id files = os.listdir(tmp_list_path) for fname in files: if fname == '.DS_Store':",
"'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA',",
"i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path",
"def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year = latest_year i",
"'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC',",
"tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path):",
"os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list (paper version >= 2) cates",
"'a') as json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in",
"(paper version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC',",
"if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list (paper version >=",
"preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by paper",
"new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return",
"'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}',",
"'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR',",
"by paper id files = os.listdir(tmp_list_path) for fname in files: if fname ==",
"latest_year i = 0 while year > end_year: print(f\"Results {i} - {i+max_results}:\") result",
"'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL',",
"int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i +=",
"result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id and N",
"year > end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query = query, start",
"with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f) outs = generate_json_file(preprint_list, tmp_file_path, domain)",
"result = arxiv.query(query = query, start = i, sort_by = 'submittedDate', sort_order =",
"= arxiv.query(query = query, start = i, sort_by = 'submittedDate', sort_order = 'descending',",
"id list (paper version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates +=",
"'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM',",
"['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB',",
"json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1, max_ver):",
"{} year = latest_year i = 0 while year > end_year: print(f\"Results {i}",
"continue tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\":",
"max_results=1000) # extract paper abstract by paper id files = os.listdir(tmp_list_path) for fname",
"max_results = max_results) new_papers = 0 for paper in result: arxiv_id = paper.id.split('/')[-1]",
"extract paper abstract by paper id files = os.listdir(tmp_list_path) for fname in files:",
"not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get",
"print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file,",
"print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query = query, start = i, sort_by",
"max_results time.sleep(3) print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file:",
"= latest_year i = 0 while year > end_year: print(f\"Results {i} - {i+max_results}:\")",
"time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path",
"generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys(): max_ver",
"= get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by paper id",
"'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL',",
"for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1, max_ver): print(ID)",
"'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH',",
"+= ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM',",
"fname in files: if fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain) with",
"os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw",
"os import time import json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000):",
"int(arxiv_id[-1]) if '.' in arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '')",
"\"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__",
"'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG',",
"'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN',",
"'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE',",
"break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list,",
"'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list",
"= fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f) outs =",
"source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv'",
"try: source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get paper {ID}!!!')",
"get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year = latest_year i =",
"'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL',",
"and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year",
"arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if arxiv_id",
"'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021,",
"paper id list (paper version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates",
"'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF',",
"json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a')",
"= 0 for paper in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if",
"'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA',",
"= ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs =",
"'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO',",
"arxiv.query(query = query, start = i, sort_by = 'submittedDate', sort_order = 'descending', max_results",
"if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2)",
"'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC',",
"'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for",
"'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT',",
"while year > end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query = query,",
"= i, sort_by = 'submittedDate', sort_order = 'descending', max_results = max_results) new_papers =",
"def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys():",
"in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\",",
"os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list (paper",
"else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers == 0: break with",
"'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE',",
"papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary except:",
"'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC',",
"= max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 =",
"1 year = int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else:",
"get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by paper id files",
"'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR',",
"0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return outs def",
"tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs,",
"arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1",
"= { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, }",
"'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates:",
"N = int(arxiv_id[-1]) if '.' in arxiv_id and N > 1: arxiv_id =",
"'submittedDate', sort_order = 'descending', max_results = max_results) new_papers = 0 for paper in",
"year = int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N)",
"\"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path",
"tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path)",
"start = i, sort_by = 'submittedDate', sort_order = 'descending', max_results = max_results) new_papers",
"= '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if",
"'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY']",
"in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1 =",
"cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper",
"papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue tmp = { \"arxiv_id\": ID,",
"> 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4])",
"latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by paper id files = os.listdir(tmp_list_path)",
"+= ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM',",
"'cs.SC', 'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000)",
"cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates",
"'descending', max_results = max_results) new_papers = 0 for paper in result: arxiv_id =",
"as json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1,",
"\"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__':",
"N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year =",
"preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs",
"{i} - {i+max_results}:\") result = arxiv.query(query = query, start = i, sort_by =",
"import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year =",
"with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path,",
"= 0 while year > end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query",
"'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN',",
"arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if arxiv_id not in",
"[N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers == 0: break",
"== 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return outs",
"# extract paper abstract by paper id files = os.listdir(tmp_list_path) for fname in",
"tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not",
"__name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if",
"domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year = latest_year i = 0",
"if fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as",
"= 'submittedDate', sort_order = 'descending', max_results = max_results) new_papers = 0 for paper",
"'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\",",
"cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract by",
"= ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs =",
"json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file:",
"'.' in arxiv_id and N > 1: arxiv_id = arxiv_id.replace(f'v{N}', '') print(arxiv_id) new_papers",
"'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT',",
"os.listdir(tmp_list_path) for fname in files: if fname == '.DS_Store': continue domain = fname.split('_')[0]",
"fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f:",
"= '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path):",
"'../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if",
"= int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i",
"if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw'",
"= [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers == 0:",
"'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET',",
"if arxiv_id not in outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results",
"arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id and N >",
"'') print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if arxiv_id not in outs.keys():",
"= papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue tmp = { \"arxiv_id\":",
"outs.keys(): outs[arxiv_id] = [N] else: outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers",
"query, start = i, sort_by = 'submittedDate', sort_order = 'descending', max_results = max_results)",
"if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id",
"in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) # extract paper abstract",
"ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if",
"'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO', 'cs.SI', 'cs.SE', 'cs.SD', 'cs.SC', 'cs.SY'] for cate in",
"open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i",
"'../data/arxiv/raw' if not os.path.isdir(tmp_path): os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path)",
"abstract by paper id files = os.listdir(tmp_list_path) for fname in files: if fname",
"os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list (paper version",
"\"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path =",
"== '.DS_Store': continue domain = fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list",
"max_results=1000): outs = {} year = latest_year i = 0 while year >",
"} time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ == '__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list'",
"paper {ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\":",
"outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in",
"import time import json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs",
"'q-fin.TR'] cates += ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO']",
"outs[arxiv_id].append(N) i += max_results time.sleep(3) print(year) if new_papers == 0: break with open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json',",
"paper abstract by paper id files = os.listdir(tmp_list_path) for fname in files: if",
"latest_year=2021, end_year=2010, max_results=1000): outs = {} year = latest_year i = 0 while",
"'cs.SY'] for cate in cates: preprint_list = get_paper_list(query=f\"cat:{cate}\", domain=f'{cate}', latest_year=2021, end_year=1900, max_results=1000) #",
"print(f'Fail to get paper {ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\": i,",
"+= ['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates +=",
"arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year = latest_year",
"json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {} year",
"in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1]) if '.' in arxiv_id and",
"open(f'../data/arxiv/list/{domain}_list_{len(outs)}.json', 'w') as json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain):",
"'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS',",
"i, \"after_version\": i+1, \"before_raw_txt\": source_abs, \"after_raw_txt\": target_abs, } time.sleep(3) json_file.write(json.dumps(tmp)+'\\n') if __name__ ==",
"i, sort_by = 'submittedDate', sort_order = 'descending', max_results = max_results) new_papers = 0",
"['q-bio.BM', 'q-bio.CB', 'q-bio.GN', 'q-bio.MN', 'q-bio.NC', 'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI',",
"version >= 2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN',",
"end_year=1900, max_results=1000) # extract paper abstract by paper id files = os.listdir(tmp_list_path) for",
"'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR']",
"'cs.LO', 'cs.LG', 'cs.MS', 'cs.MA', 'cs.MM', 'cs.NI', 'cs.NE', 'cs.NA', 'cs.OS', 'cs.OH', 'cs.PF', 'cs.PL', 'cs.RO',",
"except: print(f'Fail to get paper {ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\":",
"fname.split('_')[0] print(domain) with open(f'{tmp_list_path}/{fname}', 'r') as f: preprint_list = json.load(f) outs = generate_json_file(preprint_list,",
"get raw paper id list (paper version >= 2) cates = ['econ.EM', 'econ.GN',",
"print(arxiv_id) new_papers += 1 year = int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id]",
"json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as",
"= {} year = latest_year i = 0 while year > end_year: print(f\"Results",
"ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for i in range(1, max_ver): print(ID) preprint_v1",
"= ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM',",
"not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper id list",
"'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.TR'] cates",
"'cs.CR', 'cs.DS', 'cs.DB', 'cs.DL', 'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR',",
"'__main__': tmp_path = '../data/arxiv' tmp_list_path = '../data/arxiv/list' tmp_file_path = '../data/arxiv/raw' if not os.path.isdir(tmp_path):",
"tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys(): max_ver =",
"new_papers = 0 for paper in result: arxiv_id = paper.id.split('/')[-1] N = int(arxiv_id[-1])",
"'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV', 'cs.CY', 'cs.CR', 'cs.DS', 'cs.DB',",
"papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get paper {ID}!!!') continue tmp =",
"{ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1, \"before_raw_txt\": source_abs,",
"'w') as json_file: json.dump(outs, json_file, indent=2) return outs def generate_json_file(preprint_list, tmp_file_path, domain): with",
"2) cates = ['econ.EM', 'econ.GN', 'econ.TH'] cates += ['q-fin.CP', 'q-fin.EC', 'q-fin.GN', 'q-fin.MF', 'q-fin.PM',",
"import json import arxiv def get_paper_list(query=\"cat:cs.CL\", domain='cscl', latest_year=2021, end_year=2010, max_results=1000): outs = {}",
"'cs.DM', 'cs.DC', 'cs.ET', 'cs.FL', 'cs.GL', 'cs.GR', 'cs.AR', 'cs.HC', 'cs.IR', 'cs.IT', 'cs.LO', 'cs.LG', 'cs.MS',",
"print(ID) preprint_v1 = ID+f'v{i}' preprint_v2 = ID+f'v{i+1}' papers = arxiv.query(query=\"\", id_list=[preprint_v1,preprint_v2], max_results=2) try:",
"with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID in preprint_list.keys(): max_ver = max(preprint_list[ID]) for",
"'q-bio.OT', 'q-bio.PE', 'q-bio.QM', 'q-bio.SC', 'q-bio.TO'] cates += ['cs.AI', 'cs.CC', 'cs.CE', 'cs.CG', 'cs.GT', 'cs.CV',",
"return outs def generate_json_file(preprint_list, tmp_file_path, domain): with open(f'{tmp_file_path}/raw_revisions_{domain}.json', 'a') as json_file: for ID",
"max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get paper",
"id_list=[preprint_v1,preprint_v2], max_results=2) try: source_abs = papers[0].summary target_abs = papers[1].summary except: print(f'Fail to get",
"for fname in files: if fname == '.DS_Store': continue domain = fname.split('_')[0] print(domain)",
"os.mkdir(tmp_path) if not os.path.isdir(tmp_list_path): os.mkdir(tmp_list_path) if not os.path.isdir(tmp_file_path): os.mkdir(tmp_file_path) # get raw paper",
"new_papers += 1 year = int(paper.updated[:4]) if arxiv_id not in outs.keys(): outs[arxiv_id] =",
"> end_year: print(f\"Results {i} - {i+max_results}:\") result = arxiv.query(query = query, start =",
"get paper {ID}!!!') continue tmp = { \"arxiv_id\": ID, \"before_version\": i, \"after_version\": i+1,"
] |
[
"p_opts, s_opts) # Solve try: sol = opti.solve() except RuntimeError: sol = opti.debug",
"upper bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if",
"chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"),",
"you should get: (XFLR5) # CL = 0.797 # CDi = 0.017 #",
"y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0,",
"airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3,",
"Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0,",
"constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm ==",
"airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG location",
"opti.variable() opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var >= lb) if ub",
"edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap",
"opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var airplane = Airplane( name=\"AVL's plane.avl\",",
":param lb: Optional lower bound :param ub: Optional upper bound :return: The created",
"10) ap = Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377,",
"beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up the VLM optimization",
"# Extra constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist,",
"ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should get: (XFLR5) # CL =",
"except RuntimeError: sol = opti.debug # Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol)",
"# Control surfaces are applied between attrib_name given XSec and the next one.",
"Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross",
"Postprocess ap_sol.draw() # Answer you should get: (XFLR5) # CL = 0.797 #",
"ap.op_point.alpha) * 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts",
"# Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric',",
"), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root",
"aerosandbox import * opti = cas.Opti() # Initialize an optimization environment def variable(init_val,",
"y_ref=0, # CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing(",
"ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1",
"= opti.variable() opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var >= lb) if",
"chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16,",
") ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec(",
"ub is not None: opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\" Initialize",
"chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ),",
"# root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator",
"cas.Opti() # Initialize an optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name",
"the VLM optimization submatrix ap.setup() # Extra constraints # Trim constraint opti.subject_to([ ap.CL",
"s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of the wing's",
"0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ]",
"RuntimeError: sol = opti.debug # Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) #",
"0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5,",
"Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', #",
"control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec( # Mid",
"CG location y_ref=0, # CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15,",
"airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1,",
"leading edge y_le=0, # Coordinates of the wing's leading edge z_le=0, # Coordinates",
"op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set",
"alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up the VLM",
"chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal",
"0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces",
"twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( #",
"to the wing's leading edge. y_le=0, # Coordinates of the XSec's leading edge,",
"Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0),",
"# CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates",
"# ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[",
"y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec(",
"val) opti.subject_to(var == val) return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, #",
"\"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol =",
"Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0,",
"z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75",
"= 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol = opti.solve() except RuntimeError:",
"ub=None): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess :param lb:",
"x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4,",
"the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ),",
"Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1,",
"), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] )",
"Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG location z_ref=0.2239, #",
"the wing's leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"),",
"]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective",
"x_le=0, # Coordinates of the wing's leading edge y_le=0, # Coordinates of the",
"leading edge, relative to the wing's leading edge. chord=1, # 0.18, twist=4, #",
"# CG location y_ref=0, # CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1,",
"Flap # Control surfaces are applied between attrib_name given XSec and the next",
"variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are applied between",
"# degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are applied between attrib_name",
"= 1e6 # If you need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"]",
"degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5,",
"# # ap.Cl == 0, # ap.Cm == 0, # # ap.Cn ==",
"not None: opti.subject_to(var >= lb) if ub is not None: opti.subject_to(var <= ub)",
"environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable. :param init_val:",
"val) return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0,",
"between attrib_name given XSec and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, #",
"up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ),",
"relative to the wing's leading edge. z_le=0, # Coordinates of the XSec's leading",
"), opti=opti ) # Set up the VLM optimization submatrix ap.setup() # Extra",
"submatrix ap.setup() # Extra constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist",
"wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates of the XSec's",
"x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6,",
"leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections WingXSec( #",
"WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', #",
"not None: opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar",
"== 0, # # ap.Cn == 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm,",
"# Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0,",
"s_opts[\"max_iter\"] = 1e6 # If you need to interrupt, just use ctrl+c #",
"opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable.",
"= \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol",
"Control surfaces are applied between attrib_name given XSec and the next one. control_surface_deflection=0,",
"x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical",
"# as chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7,",
"spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ]",
"import * opti = cas.Opti() # Initialize an optimization environment def variable(init_val, lb=None,",
"WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1,",
"is not None: opti.subject_to(var >= lb) if ub is not None: opti.subject_to(var <=",
"variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip #",
"# ap.Cm == 0, # # ap.Cn == 0, ]) # Cmalpha constraint",
"plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG location z_ref=0.2239, # CG location",
"lb: Optional lower bound :param ub: Optional upper bound :return: The created variable",
":param init_val: Initial guess :param lb: Optional lower bound :param ub: Optional upper",
"z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60,",
"airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2,",
"# s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve",
"density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up the",
"Optional upper bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, val)",
"CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of",
"XSec and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction",
"options p_opts = {} s_opts = {} s_opts[\"max_iter\"] = 1e6 # If you",
"the wing's leading edge. y_le=0, # Coordinates of the XSec's leading edge, relative",
"ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should get: (XFLR5)",
"ap.Cn == 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi ==",
"-1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts =",
"twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1(",
"Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, #",
"z_le=0, # Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The",
"xsecs=[ # The wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates",
"Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts = {} s_opts[\"max_iter\"]",
"= opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var airplane = Airplane( name=\"AVL's",
"the XSec's leading edge, relative to the wing's leading edge. chord=1, # 0.18,",
"edge, relative to the wing's leading edge. z_le=0, # Coordinates of the XSec's",
"control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60),",
"airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) #",
"of the XSec's leading edge, relative to the wing's leading edge. z_le=0, #",
"CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\",",
"XSec's leading edge, relative to the wing's leading edge. chord=1, # 0.18, twist=4,",
"* 0.5, # # ap.CY == 0, # # ap.Cl == 0, #",
"scalar design variable. :param init_val: Initial guess :param lb: Optional lower bound :param",
"# x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), #",
"= Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG location z_ref=0.2239,",
"var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess",
"def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial",
"opti.solver('ipopt', p_opts, s_opts) # Solve try: sol = opti.solve() except RuntimeError: sol =",
"# 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), #",
"var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var airplane = Airplane(",
"WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"),",
"variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var",
"The created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb is not",
"opti.subject_to(var == val) return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG",
"ap.CY == 0, # # ap.Cl == 0, # ap.Cm == 0, #",
"== 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 *",
"init_val: Initial guess :param lb: Optional lower bound :param ub: Optional upper bound",
"airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are applied between attrib_name given XSec",
"symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25,",
"bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var ==",
"leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', #",
"# Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective #",
"# s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt',",
"quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess :param lb:",
"edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections WingXSec( # Root",
"XSec's leading edge, relative to the wing's leading edge. y_le=0, # Coordinates of",
"None: opti.subject_to(var >= lb) if ub is not None: opti.subject_to(var <= ub) return",
"lb) if ub is not None: opti.subject_to(var <= ub) return var def quasi_variable(val):",
"(\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates of the XSec's leading edge,",
"60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1,",
"chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0,",
"ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param init_val:",
"chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec(",
"var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG",
"# Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's",
"0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), #",
"of the wing's leading edge z_le=0, # Coordinates of the wing's leading edge",
"surfaces are applied between attrib_name given XSec and the next one. control_surface_deflection=0, #",
"wing's leading edge y_le=0, # Coordinates of the wing's leading edge z_le=0, #",
"x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75,",
"tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing(",
"180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {}",
"Answer you should get: (XFLR5) # CL = 0.797 # CDi = 0.017",
"if ub is not None: opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\"",
"ap.setup() # Extra constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist ==",
"0, # # ap.Cl == 0, # ap.Cm == 0, # # ap.Cn",
"of the XSec's leading edge, relative to the wing's leading edge. y_le=0, #",
"location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0,",
"WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ]",
"twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are",
"] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1,",
"opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options",
"= opti.solve() except RuntimeError: sol = opti.debug # Create solved object ap_sol =",
"solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should",
"edge. y_le=0, # Coordinates of the XSec's leading edge, relative to the wing's",
"-60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False,",
"edge z_le=0, # Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ #",
"x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron",
"# Flap # Control surfaces are applied between attrib_name given XSec and the",
"edge. z_le=0, # Coordinates of the XSec's leading edge, relative to the wing's",
"Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0,",
"should get: (XFLR5) # CL = 0.797 # CDi = 0.017 # CL/CDi",
"# degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175,",
"sections WingXSec( # Root x_le=-0.25, # Coordinates of the XSec's leading edge, relative",
"return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial",
"), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") )",
"copy from aerosandbox import * opti = cas.Opti() # Initialize an optimization environment",
"# tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ),",
"# Postprocess ap_sol.draw() # Answer you should get: (XFLR5) # CL = 0.797",
"Initial guess :param lb: Optional lower bound :param ub: Optional upper bound :return:",
"velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up",
"control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ]",
"twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5,",
"from aerosandbox import * opti = cas.Opti() # Initialize an optimization environment def",
"edge, relative to the wing's leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10),",
"chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap #",
"= \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts)",
"ap = Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0),",
"ub: Optional upper bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var,",
"(XFLR5) # CL = 0.797 # CDi = 0.017 # CL/CDi = 47.211",
"leading edge, relative to the wing's leading edge. y_le=0, # Coordinates of the",
"constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) #",
"Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2),",
"# Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\")",
"attrib_name scalar design variable. :param init_val: Initial guess :param lb: Optional lower bound",
"1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"),",
"# Root x_le=-0.25, # Coordinates of the XSec's leading edge, relative to the",
"chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0,",
"wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections WingXSec(",
"Wing( name=\"Main Wing\", x_le=0, # Coordinates of the wing's leading edge y_le=0, #",
"Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0),",
"spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, #",
">= lb) if ub is not None: opti.subject_to(var <= ub) return var def",
"= cas.Opti() # Initialize an optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize",
"constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2]",
"x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"),",
"applied between attrib_name given XSec and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75,",
"# Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16),",
"lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess :param",
"interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" #",
"Initialize attrib_name scalar design variable. :param init_val: Initial guess :param lb: Optional lower",
"# Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts = {}",
"guess :param lb: Optional lower bound :param ub: Optional upper bound :return: The",
"# ap.Cl == 0, # ap.Cm == 0, # # ap.Cn == 0,",
"Solve try: sol = opti.solve() except RuntimeError: sol = opti.debug # Create solved",
"r=quasi_variable(0), ), opti=opti ) # Set up the VLM optimization submatrix ap.setup() #",
"up the VLM optimization submatrix ap.setup() # Extra constraints # Trim constraint opti.subject_to([",
"variable. :param init_val: Initial guess :param lb: Optional lower bound :param ub: Optional",
"z_le=0, # Coordinates of the XSec's leading edge, relative to the wing's leading",
"opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var >= lb) if ub is",
"leading edge. z_le=0, # Coordinates of the XSec's leading edge, relative to the",
"WingXSec( # Root x_le=-0.25, # Coordinates of the XSec's leading edge, relative to",
"0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol = opti.solve() except RuntimeError: sol",
"ap_sol.draw() # Answer you should get: (XFLR5) # CL = 0.797 # CDi",
"\"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess :param lb: Optional",
"twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1,",
"created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb is not None:",
"control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0,",
"Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you",
"opti=opti ) # Set up the VLM optimization submatrix ap.setup() # Extra constraints",
"you need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"]",
"Coordinates of the wing's leading edge z_le=0, # Coordinates of the wing's leading",
"use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] =",
"design variable. :param init_val: Initial guess :param lb: Optional lower bound :param ub:",
"), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0,",
"z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap",
"the XSec's leading edge, relative to the wing's leading edge. y_le=0, # Coordinates",
"lb is not None: opti.subject_to(var >= lb) if ub is not None: opti.subject_to(var",
"= Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0),",
"\"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var airplane =",
"0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY == 0, #",
"\"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var >=",
"s_opts = {} s_opts[\"max_iter\"] = 1e6 # If you need to interrupt, just",
"= {} s_opts[\"max_iter\"] = 1e6 # If you need to interrupt, just use",
"edge y_le=0, # Coordinates of the wing's leading edge z_le=0, # Coordinates of",
"Coordinates of the XSec's leading edge, relative to the wing's leading edge. chord=1,",
"airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( #",
"{} s_opts = {} s_opts[\"max_iter\"] = 1e6 # If you need to interrupt,",
"control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0,",
"0.5, # # ap.CY == 0, # # ap.Cl == 0, # ap.Cm",
"control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5,",
"opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] ==",
"object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should get:",
"spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\")",
"== 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1)",
"is not None: opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name",
") ] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up the",
"0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01,",
"== val) return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location",
"y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0,",
"] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( #",
":return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val)",
"0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\",",
"edge, relative to the wing's leading edge. y_le=0, # Coordinates of the XSec's",
"z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, #",
"Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), #",
"# opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts = {} s_opts[\"max_iter\"] =",
"as chord fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, #",
"If you need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" #",
"ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY ==",
"control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5,",
"ap.Cm == 0, # # ap.Cn == 0, ]) # Cmalpha constraint #",
"upper bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var",
"variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var airplane",
"wing's leading edge. y_le=0, # Coordinates of the XSec's leading edge, relative to",
"x_ref=0.02463, # CG location y_ref=0, # CG location z_ref=0.2239, # CG location s_ref=12,",
"= copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should get: (XFLR5) #",
"# # ap.CY == 0, # # ap.Cl == 0, # ap.Cm ==",
"get: (XFLR5) # CL = 0.797 # CDi = 0.017 # CL/CDi =",
"chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25, #",
"opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts = {} s_opts[\"max_iter\"] = 1e6",
"opti = cas.Opti() # Initialize an optimization environment def variable(init_val, lb=None, ub=None): \"\"\"",
"leading edge. y_le=0, # Coordinates of the XSec's leading edge, relative to the",
"fraction spanwise_panels=16, ), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4,",
"control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0, -60,",
"# z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), #",
"== 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY == 0,",
"# WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), #",
"== ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # #",
"chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0,",
"airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[",
"twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5,",
"wing's leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem',",
"WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) #",
"name=\"Vertical Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4,",
"s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol = opti.solve() except",
"xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75,",
"* opti = cas.Opti() # Initialize an optimization environment def variable(init_val, lb=None, ub=None):",
"control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] )",
"opti.debug # Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() #",
"b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of the wing's leading edge",
"y_le=0, # Coordinates of the XSec's leading edge, relative to the wing's leading",
"# Solve try: sol = opti.solve() except RuntimeError: sol = opti.debug # Create",
"location y_ref=0, # CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[",
"to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\"",
"Coordinates of the XSec's leading edge, relative to the wing's leading edge. y_le=0,",
"location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of the",
"copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer you should get: (XFLR5) # CL",
"60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075,",
"Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0])",
"leading edge z_le=0, # Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[",
":param ub: Optional upper bound :return: The created variable \"\"\" var = opti.variable()",
"xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem',",
"== 0, # # ap.Cl == 0, # ap.Cm == 0, # #",
"symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder",
"-ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY == 0, # # ap.Cl",
"Set up the VLM optimization submatrix ap.setup() # Extra constraints # Trim constraint",
"cross (\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates of the XSec's leading",
"0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1),",
"wing's leading edge. z_le=0, # Coordinates of the XSec's leading edge, relative to",
"sol = opti.solve() except RuntimeError: sol = opti.debug # Create solved object ap_sol",
"control_surface_type='symmetric_problem', # Flap # Control surfaces are applied between attrib_name given XSec and",
"control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1,",
"# 0.18, twist=4, # variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control",
"if lb is not None: opti.subject_to(var >= lb) if ub is not None:",
"# y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), #",
"relative to the wing's leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), #",
"p_opts = {} s_opts = {} s_opts[\"max_iter\"] = 1e6 # If you need",
"Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") )",
"of the wing's leading edge y_le=0, # Coordinates of the wing's leading edge",
"# ap.CY == 0, # # ap.Cl == 0, # ap.Cm == 0,",
"), WingXSec( # Mid x_le=-0.175, y_le=7.5, z_le=0.5, chord=0.7, # 0.16, twist=4, # variable(0,-10,10),",
"# variable(0,-10,10), # degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are applied",
"# Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0),",
"created variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return var",
"init_val) if lb is not None: opti.subject_to(var >= lb) if ub is not",
"x_le=-0.25, # Coordinates of the XSec's leading edge, relative to the wing's leading",
"# Coordinates of the wing's leading edge z_le=0, # Coordinates of the wing's",
"airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65,",
"9.81 * 0.5, # # ap.CY == 0, # # ap.Cl == 0,",
"the AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti",
"0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ),",
"control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075, y_le=0, z_le=1, chord=0.3, twist=0,",
"# Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw() # Answer",
"wing's leading edge z_le=0, # Coordinates of the wing's leading edge symmetric=True, chordwise_panels=1,",
"WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10",
"# twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0,",
"== 9.81 * 0.5, # # ap.CY == 0, # # ap.Cl ==",
"# Solver options p_opts = {} s_opts = {} s_opts[\"max_iter\"] = 1e6 #",
"Coordinates of the XSec's leading edge, relative to the wing's leading edge. z_le=0,",
"need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] =",
"the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\") sections",
") # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up the AeroProblem airplane=airplane,",
"# airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up the AeroProblem airplane=airplane, op_point=OperatingPoint(",
"# variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip",
"chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap =",
"y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10),",
"] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up the AeroProblem",
"Optional lower bound :param ub: Optional upper bound :return: The created variable \"\"\"",
") # Set up the VLM optimization submatrix ap.setup() # Extra constraints #",
") ] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set",
"leading edge, relative to the wing's leading edge. z_le=0, # Coordinates of the",
"just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"]",
"Optional upper bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val)",
"var = opti.variable() opti.set_initial(var, init_val) if lb is not None: opti.subject_to(var >= lb)",
"z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', #",
"z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ),",
"opti.set_initial(var, val) opti.subject_to(var == val) return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463,",
"attrib_name given XSec and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as",
"the wing's leading edge z_le=0, # Coordinates of the wing's leading edge symmetric=True,",
"# The wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates of",
"= opti.debug # Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess ap_sol.draw()",
"optimization submatrix ap.setup() # Extra constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510,",
"# chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing(",
"# Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3,",
"ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, #",
"z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\", x_le=6,",
"Solver options p_opts = {} s_opts = {} s_opts[\"max_iter\"] = 1e6 # If",
"opti.solve() except RuntimeError: sol = opti.debug # Create solved object ap_sol = copy.deepcopy(ap)",
"to the wing's leading edge. chord=1, # 0.18, twist=4, # variable(0,-10,10), # degrees",
"x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25), # z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08,",
"try: sol = opti.solve() except RuntimeError: sol = opti.debug # Create solved object",
"ap.Cl == 0, # ap.Cm == 0, # # ap.Cn == 0, ])",
") ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec(",
"s_opts) # Solve try: sol = opti.solve() except RuntimeError: sol = opti.debug #",
"p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up the VLM optimization submatrix",
"c_ref=1, b_ref=15, wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of the wing's leading",
"\"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) #",
"= {} s_opts = {} s_opts[\"max_iter\"] = 1e6 # If you need to",
"# If you need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] = \"adaptive\"",
"Wing\", x_le=0, # Coordinates of the wing's leading edge y_le=0, # Coordinates of",
"== 0, # ap.Cm == 0, # # ap.Cn == 0, ]) #",
"s_opts[\"mu_strategy\"] = \"adaptive\" # s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts,",
"1e6 # If you need to interrupt, just use ctrl+c # s_opts[\"mu_strategy\"] =",
"None: opti.subject_to(var <= ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design",
"wings=[ Wing( name=\"Main Wing\", x_le=0, # Coordinates of the wing's leading edge y_le=0,",
"name=\"Main Wing\", x_le=0, # Coordinates of the wing's leading edge y_le=0, # Coordinates",
"ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81",
"== -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts = {} s_opts",
"), # WingXSec( # Tip # x_c=0.08,#variable(0.08, 0, 0.16), # y_c=1,#variable(1, 0.5, 1.25),",
"variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess",
"z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( x_le=-0.075,",
"y_le=0, # Coordinates of the wing's leading edge z_le=0, # Coordinates of the",
"The wing's cross (\"X\") sections WingXSec( # Root x_le=-0.25, # Coordinates of the",
"Extra constraints # Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm",
"y_le=2, z_le=0, chord=0.3, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\") ) ] ), Wing( name=\"Vertical Stabilizer\",",
"# s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try: sol = opti.solve()",
"name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0,",
"q=quasi_variable(0), r=quasi_variable(0), ), opti=opti ) # Set up the VLM optimization submatrix ap.setup()",
"# ap.Cn == 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi",
"opti.subject_to(var >= lb) if ub is not None: opti.subject_to(var <= ub) return var",
"-60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip",
"VLM optimization submatrix ap.setup() # Extra constraints # Trim constraint opti.subject_to([ ap.CL ==",
"sol = opti.debug # Create solved object ap_sol = copy.deepcopy(ap) ap_sol.substitute_solution(sol) # Postprocess",
"Initialize an optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design",
"* 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver options p_opts =",
"0, # ap.Cm == 0, # # ap.Cn == 0, ]) # Cmalpha",
"of the wing's leading edge symmetric=True, chordwise_panels=1, xsecs=[ # The wing's cross (\"X\")",
"{} s_opts[\"max_iter\"] = 1e6 # If you need to interrupt, just use ctrl+c",
"# opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) # Objective # opti.minimize(-ap.force_total_inviscid_wind[0]) # Solver",
"Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ), WingXSec( # tip x_le=-0.075, y_le=2, z_le=0, chord=0.3, twist=variable(0,",
"degrees airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Flap # Control surfaces are applied between attrib_name given",
"# # ap.Cn == 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) *",
"0, # # ap.Cn == 0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha)",
"optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable. :param",
"airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( # Tip # x_c=0.08,#variable(0.08,",
":return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb is",
"0.16, twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec(",
"AeroProblem airplane=airplane, op_point=OperatingPoint( velocity=65, density=0.002377, alpha=variable(0), beta=quasi_variable(0), p=quasi_variable(0), q=quasi_variable(0), r=quasi_variable(0), ), opti=opti )",
"next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec(",
"# -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY == 0, # #",
"# airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6, y_le=0, z_le=0.5, symmetric=True,",
"y_le=0, z_le=1, chord=0.3, twist=0, airfoil=Airfoil(name=\"naca0012\") ) ] ) ] ) # airplane.set_paneling_everywhere(6, 10)",
"# Set up the VLM optimization submatrix ap.setup() # Extra constraints # Trim",
"XSec's leading edge, relative to the wing's leading edge. z_le=0, # Coordinates of",
"z_c=0.1,#variable(0.1, 0, 0.2), # chord=variable(0.08,0,1),#0.08,#variable(0.08, 0.01, 1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # )",
"# Answer you should get: (XFLR5) # CL = 0.797 # CDi =",
"def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param init_val: Initial guess :param",
"are applied between attrib_name given XSec and the next one. control_surface_deflection=0, # degrees",
"The created variable \"\"\" var = opti.variable() opti.set_initial(var, val) opti.subject_to(var == val) return",
"symmetric=True, chordwise_panels=1, xsecs=[ WingXSec( # root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60),",
"twist=4, # variable(0,-10,10), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='asymmetric', # Aileron control_surface_deflection=0, control_surface_hinge_point=0.75 ), # WingXSec( #",
"# Trim constraint opti.subject_to([ ap.CL == 0.390510, ap.airplane.wings[1].xsecs[0].twist == ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0,",
"of the XSec's leading edge, relative to the wing's leading edge. chord=1, #",
"# CG location z_ref=0.2239, # CG location s_ref=12, c_ref=1, b_ref=15, wings=[ Wing( name=\"Main",
"the XSec's leading edge, relative to the wing's leading edge. z_le=0, # Coordinates",
"x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Rudder control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10 ),",
"to the wing's leading edge. z_le=0, # Coordinates of the XSec's leading edge,",
"1), # twist=0,#variable(0,-10,10), # airfoil=Airfoil(name=\"naca4412\"), # ) ] ), Wing( name=\"Horizontal Stabilizer\", x_le=6,",
"import copy from aerosandbox import * opti = cas.Opti() # Initialize an optimization",
"name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, # CG location z_ref=0.2239, # CG",
"given XSec and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord",
"<= ub) return var def quasi_variable(val): \"\"\" Initialize attrib_name scalar design variable. :param",
"# Coordinates of the XSec's leading edge, relative to the wing's leading edge.",
"y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0, control_surface_hinge_point=0.75, spanwise_panels=10",
"an optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar design variable.",
"relative to the wing's leading edge. y_le=0, # Coordinates of the XSec's leading",
"Coordinates of the wing's leading edge y_le=0, # Coordinates of the wing's leading",
"one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16, ), WingXSec( #",
"bound :return: The created variable \"\"\" var = opti.variable() opti.set_initial(var, init_val) if lb",
"y_le=0, z_le=0.5, symmetric=False, chordwise_panels=1, xsecs=[ WingXSec( x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=0, airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem',",
"# Coordinates of the wing's leading edge y_le=0, # Coordinates of the wing's",
"the wing's leading edge. z_le=0, # Coordinates of the XSec's leading edge, relative",
"the wing's leading edge y_le=0, # Coordinates of the wing's leading edge z_le=0,",
"ap.airplane.wings[1].xsecs[1].twist, ap.Cm == 0, # -ap.force_total_inviscid_wind[2] == 9.81 * 0.5, # # ap.CY",
"lower bound :param ub: Optional upper bound :return: The created variable \"\"\" var",
"] ) ] ) # airplane.set_paneling_everywhere(6, 10) ap = Casvlm1( # Set up",
"Root x_le=-0.25, # Coordinates of the XSec's leading edge, relative to the wing's",
"bound :param ub: Optional upper bound :return: The created variable \"\"\" var =",
"root x_le=-0.1, y_le=0, z_le=0, chord=0.4, twist=variable(0, -60, 60), airfoil=Airfoil(name=\"naca0012\"), control_surface_type='symmetric_problem', # Elevator control_surface_deflection=0,",
"s_opts[\"start_with_resto\"] = \"yes\" # s_opts[\"required_infeasibility_reduction\"] = 0.1 opti.solver('ipopt', p_opts, s_opts) # Solve try:",
"# Initialize an optimization environment def variable(init_val, lb=None, ub=None): \"\"\" Initialize attrib_name scalar",
"return var airplane = Airplane( name=\"AVL's plane.avl\", x_ref=0.02463, # CG location y_ref=0, #",
"0, ]) # Cmalpha constraint # opti.subject_to(cas.gradient(ap.Cm, ap.op_point.alpha) * 180/np.pi == -1) #",
"and the next one. control_surface_deflection=0, # degrees control_surface_hinge_point=0.75, # as chord fraction spanwise_panels=16,"
] |
[
"um número para encontrar a raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada",
"raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada de {}, é {}.'.format(num, raiz))",
"math num = int(input('Digite um número para encontrar a raíz: ')) raiz =",
"num = int(input('Digite um número para encontrar a raíz: ')) raiz = math.sqrt(num)",
"para encontrar a raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada de {},",
"= int(input('Digite um número para encontrar a raíz: ')) raiz = math.sqrt(num) print('A",
"encontrar a raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada de {}, é",
"int(input('Digite um número para encontrar a raíz: ')) raiz = math.sqrt(num) print('A raíz",
"import math num = int(input('Digite um número para encontrar a raíz: ')) raiz",
"a raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada de {}, é {}.'.format(num,",
"número para encontrar a raíz: ')) raiz = math.sqrt(num) print('A raíz quadrada de"
] |
[
"\"\"\" Vikor Step 1 Calculation. \"\"\" max_score = 0 for item in report.criterion_supplier_score:",
"1 Calculation. \"\"\" si = float(si) ri = float(ri) min_si = float(min_si) max_si",
"return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation.",
"4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W value for given index.",
"= 5 Global Weight = 1 / 5 = 0.2 \"\"\" criterion_count =",
"\\ (min_score == 0 or int(item['score']) < min_score): min_score = int(item['score']) return min_score",
"value = float(get_ri_value(report, supplier)) if value > max_value: max_value = value return '%.4f'",
"index, column in enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index = index",
"max_score: max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step",
"supplier)) if min_value == 0 or value < min_value: min_value = value return",
"= float(max_ri) total = ((weight * (si - min_si)) / (max_si - min_si))",
"str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report,",
"Step 1 Calculation. \"\"\" si = float(si) ri = float(ri) min_si = float(min_si)",
"criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score = 0 for item in",
"Global Weight = 1 / 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data",
"= report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x: x != 'criterion_0', data['main_table'][0])",
"@register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for",
"supplier, weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step 1 Calculation.",
"(best - worst)) return '%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier,",
"column: criterion_index = index break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4))",
"value < min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report):",
"= score return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si,",
"- min_si)) + \\ (((1 - weight) * (ri - min_ri)) / (max_ri",
"min_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if min_value",
"5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0",
"str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight = w * float(global_weight(criterion, report))",
"= value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1",
"from matris for index, column in enumerate(columns): if 'criterion_%s' % criterion['id'] == column:",
"Calculation. \"\"\" result = filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] ==",
"max_si = float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total = ((weight *",
"normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report)) result = normalized",
"criterion) result = float((best - score) / (best - worst)) return '%.3f' %",
"score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value: max_value = score",
"== str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return 0 @register.simple_tag def",
"value = float(get_ri_value(report, supplier)) if min_value == 0 or value < min_value: min_value",
"* (si - min_si)) / (max_si - min_si)) + \\ (((1 - weight)",
"total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result",
"w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index):",
"get column index from matris for index, column in enumerate(columns): if 'criterion_%s' %",
"result = filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score)",
"1 Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_si_value(report,",
"min_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value",
"/ Criterion Count For example: W Value = 1 Criterion Count = 5",
"'%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step",
"% max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value",
"criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value:",
"break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report,",
"min_si)) + \\ (((1 - weight) * (ri - min_ri)) / (max_ri -",
"Calculation. \"\"\" total = 0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report,",
"\"\"\" si = float(si) ri = float(ri) min_si = float(min_si) max_si = float(max_si)",
"report and index. \"\"\" total = 0 for cr_id, data in report.supplier_compare.items(): criterion",
"= worst_criterion_score(report, criterion) result = float((best - score) / (best - worst)) return",
"== 0 or int(item['score']) < min_score): min_score = int(item['score']) return min_score register.filter('global_weight', global_weight)",
"(max_ri - min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor",
"criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x: x !=",
"and index. \"\"\" total = 0 for cr_id, data in report.supplier_compare.items(): criterion =",
"report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight = w * float(global_weight(criterion, report)) total",
"W Value = 1 Criterion Count = 5 Global Weight = 1 /",
"Formula: Global Weight = Criterion W value / Criterion Count For example: W",
"= report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier",
"/ (max_si - min_si)) + \\ (((1 - weight) * (ri - min_ri))",
"!= 'criterion_0', data['main_table'][0]) # get column index from matris for index, column in",
"Vikor Step 1 Calculation. \"\"\" result = filter( lambda x: x['criterion_id'] == str(criterion['id'])",
"= normalized * w return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\"",
"> max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\"",
"json from django.template import Library register = Library() def global_weight(criterion, report): \"\"\" Formula:",
"max_value = value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step",
"max_value: max_value = score return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight,",
"report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0 or int(item['score']) <",
"(max_si - min_si)) + \\ (((1 - weight) * (ri - min_ri)) /",
"float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value: max_value = score return '%.4f'",
"criterion)) w = float(global_weight(criterion, report)) result = normalized * w return '%.3f' %",
"min_ri)) / (max_ri - min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion):",
"= value return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step",
"column in enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index = index break",
"supplier in report.suppliers: value = float(get_si_value(report, supplier)) if value > max_value: max_value =",
"1 Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_si_value(report,",
"supplier, criterion)) if score > max_value: max_value = score return '%.4f' % max_value",
"1 Calculation. \"\"\" total = 0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score(",
"for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value == 0 or",
"((weight * (si - min_si)) / (max_si - min_si)) + \\ (((1 -",
"criterion)) if score > max_value: max_value = score return '%.4f' % max_value @register.simple_tag",
"in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value: max_value",
"- weight) * (ri - min_ri)) / (max_ri - min_ri)) return '%.4f' %",
"0: score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result",
"x: x != 'criterion_0', data['main_table'][0]) # get column index from matris for index,",
"total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report):",
"Weight = Criterion W value / Criterion Count For example: W Value =",
"total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0",
"\"\"\" Vikor Step 1 Calculation. \"\"\" result = filter( lambda x: x['criterion_id'] ==",
"float(si) ri = float(ri) min_si = float(min_si) max_si = float(max_si) min_ri = float(min_ri)",
"return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation.",
"filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get column index from matris for",
"0 for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id),",
"report, supplier, criterion)) w = float(global_weight(criterion, report)) result = normalized * w return",
"len(result) > 0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\"",
"> max_value: max_value = score return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier,",
"Criterion Count For example: W Value = 1 Criterion Count = 5 Global",
"Calculate supplier score for given report and index. \"\"\" total = 0 for",
"criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score = 0 for item in",
"data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x: x != 'criterion_0',",
"+= weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor",
"1 Criterion Count = 5 Global Weight = 1 / 5 = 0.2",
"= value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1",
"'%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value",
"index): \"\"\" Get W value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return",
"in enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index = index break w_value",
"@register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for",
"def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter(",
"filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result)",
"example: W Value = 1 Criterion Count = 5 Global Weight = 1",
"\"\"\" Calculate supplier score for given report and index. \"\"\" total = 0",
"Step 1 Calculation. \"\"\" total = 0 for criterion in report.get_child_criterions(): total +=",
"from django.template import Library register = Library() def global_weight(criterion, report): \"\"\" Formula: Global",
"for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score >",
"worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score = 0 for item",
"\"\"\" Formula: Global Weight = Criterion W value / Criterion Count For example:",
"@register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor",
"min_si = float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total",
"si = float(si) ri = float(ri) min_si = float(min_si) max_si = float(max_si) min_ri",
"max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\"",
"supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total = 0 for criterion in",
"* w return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step",
"1 / 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index",
"Calculation. \"\"\" max_value = 0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report,",
"lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) >",
"1 Calculation. \"\"\" min_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] ==",
"if len(result) > 0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion):",
"item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0 or int(item['score']) < min_score): min_score",
"def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step",
"@register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0",
"str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score'])",
"import division import json from django.template import Library register = Library() def global_weight(criterion,",
"index): \"\"\" Calculate supplier score for given report and index. \"\"\" total =",
"w return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1",
"enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index = index break w_value =",
"def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier",
"score > max_value: max_value = score return '%.4f' % max_value @register.simple_tag def get_qi_value(report,",
"'%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"= Criterion W value / Criterion Count For example: W Value = 1",
"@register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for",
"== str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score']",
"= Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion W value",
"Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value",
"int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result = float((best -",
"get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier in",
"min_si)) / (max_si - min_si)) + \\ (((1 - weight) * (ri -",
"data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate",
"Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w =",
"supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for criterion in",
"report)) result = normalized * w return '%.3f' % result @register.simple_tag def best_criterion_score(report,",
"value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation.",
"best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result = float((best - score)",
"1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report))",
"(ri - min_ri)) / (max_ri - min_ri)) return '%.4f' % total @register.simple_tag def",
"+= float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\"",
"% max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si, ri):",
"= 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score",
"score) / (best - worst)) return '%.3f' % result return 0 @register.simple_tag def",
"best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score = 0 for item",
"in report.suppliers: value = float(get_si_value(report, supplier)) if min_value == 0 or value <",
"in report.suppliers: value = float(get_si_value(report, supplier)) if value > max_value: max_value = value",
"\"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier in report.suppliers:",
"return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W",
"< min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\"",
"json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W value",
"0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result",
"max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\"",
"total += weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\"",
"% min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value =",
"(((1 - weight) * (ri - min_ri)) / (max_ri - min_ri)) return '%.4f'",
"Criterion Count = 5 Global Weight = 1 / 5 = 0.2 \"\"\"",
"\"\"\" Get W value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index",
"Criterion W value / Criterion Count For example: W Value = 1 Criterion",
"criterion_index = index break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag",
"\"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for criterion in report.get_child_criterions():",
"column index from matris for index, column in enumerate(columns): if 'criterion_%s' % criterion['id']",
"and \\ int(item['score']) > max_score: max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report,",
"weight = w * float(global_weight(criterion, report)) total += weight return '%.3f' % total",
"data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get",
"if score > max_value: max_value = score return '%.4f' % max_value @register.simple_tag def",
"x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return",
"si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si = float(si) ri =",
"def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total = 0 for",
"def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score = 0 for",
"supplier, criterion)) w = float(global_weight(criterion, report)) result = normalized * w return '%.3f'",
"max_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\",
"value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation.",
"% max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value =",
"str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return",
"min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si",
"max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0",
"for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if min_value == 0 or",
"if len(result) > 0: score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst =",
"max_value = value return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor",
"w = float(data['w'][index - 1]) weight = w * float(global_weight(criterion, report)) total +=",
"in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total @register.simple_tag",
"Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier))",
"\"\"\" result = filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']),",
"return '%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor",
"% total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value =",
"= float(min_ri) max_ri = float(max_ri) total = ((weight * (si - min_si)) /",
"w * float(global_weight(criterion, report)) total += weight return '%.3f' % total @register.simple_tag def",
"# get column index from matris for index, column in enumerate(columns): if 'criterion_%s'",
"weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"= float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total = ((weight * (si",
"> max_score: max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor",
"= 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if value >",
"== str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight = w * float(global_weight(criterion,",
"= float(get_si_value(report, supplier)) if value > max_value: max_value = value return '%.4f' %",
"index from matris for index, column in enumerate(columns): if 'criterion_%s' % criterion['id'] ==",
"Count = 5 Global Weight = 1 / 5 = 0.2 \"\"\" criterion_count",
"for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0",
"= 0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns",
"'%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si =",
"weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step",
"total = ((weight * (si - min_si)) / (max_si - min_si)) + \\",
"'%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value",
"len(result) > 0: score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report,",
"def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier",
"report.suppliers: value = float(get_si_value(report, supplier)) if value > max_value: max_value = value return",
"for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if value > max_value: max_value",
"value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation.",
"in report.suppliers: value = float(get_ri_value(report, supplier)) if value > max_value: max_value = value",
"int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"Step 1 Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value =",
"supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value == 0 or value",
"report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier,",
"report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index -",
"/ criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W value for",
"normalized * w return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor",
"return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"min_value == 0 or value < min_value: min_value = value return '%.4f' %",
"result = normalized * w return '%.3f' % result @register.simple_tag def best_criterion_score(report, criterion):",
"'%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation.",
"score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result =",
"\"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if",
"0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score",
"criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x:",
"- min_si)) / (max_si - min_si)) + \\ (((1 - weight) * (ri",
"= filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if",
"(min_score == 0 or int(item['score']) < min_score): min_score = int(item['score']) return min_score register.filter('global_weight',",
"W value / Criterion Count For example: W Value = 1 Criterion Count",
"% criterion['id'] == column: criterion_index = index break w_value = data['w'][criterion_index] return json.dumps(round(w_value",
"min_ri = float(min_ri) max_ri = float(max_ri) total = ((weight * (si - min_si))",
"@register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score = 0",
"report.suppliers: value = float(get_ri_value(report, supplier)) if min_value == 0 or value < min_value:",
"x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score']) best =",
"calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given report and index. \"\"\" total",
"report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total @register.simple_tag def",
"'%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si,",
"report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value: max_value =",
"return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si = float(si) ri = float(ri)",
"= float(si) ri = float(ri) min_si = float(min_si) max_si = float(max_si) min_ri =",
"Vikor Step 1 Calculation. \"\"\" max_value = 0 for criterion in report.get_child_criterions(): score",
"criterion_index = 0 columns = filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get",
"= index break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def",
"index break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion,",
"get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter( lambda",
"value return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1",
"% total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score",
"\"\"\" Vikor Step 1 Calculation. \"\"\" total = 0 for criterion in report.get_child_criterions():",
"report, supplier, criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step",
"float(global_weight(criterion, report)) result = normalized * w return '%.3f' % result @register.simple_tag def",
"\"\"\" Vikor Step 1 Calculation. \"\"\" si = float(si) ri = float(ri) min_si",
"if item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0 or int(item['score']) < min_score):",
"value = float(get_si_value(report, supplier)) if value > max_value: max_value = value return '%.4f'",
"max_ri, si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si = float(si) ri",
"< min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\"",
"result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation.",
"for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' %",
"Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier))",
"w = float(global_weight(criterion, report)) result = normalized * w return '%.3f' % result",
"get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report,",
"x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score",
"= 0 for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) ==",
"def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter(",
"max_value = 0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion))",
"x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight = w",
"supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier,",
"Step 1 Calculation. \"\"\" result = filter( lambda x: x['criterion_id'] == str(criterion['id']) and",
"return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"\"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier in report.suppliers:",
"value > max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report):",
"float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total = ((weight",
"x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return 0 @register.simple_tag",
"Vikor Step 1 Calculation. \"\"\" min_score = 0 for item in report.criterion_supplier_score: if",
"= 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if value >",
"ri = float(ri) min_si = float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri",
"Vikor Step 1 Calculation. \"\"\" total = 0 for criterion in report.get_child_criterions(): total",
"- worst)) return '%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion):",
"str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight = w *",
"report, supplier, criterion)) if score > max_value: max_value = score return '%.4f' %",
"min_value = value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step",
"return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for",
"Vikor Step 1 Calculation. \"\"\" si = float(si) ri = float(ri) min_si =",
"import json from django.template import Library register = Library() def global_weight(criterion, report): \"\"\"",
"1 Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report,",
"report.suppliers: value = float(get_ri_value(report, supplier)) if value > max_value: max_value = value return",
"min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1",
"Step 1 Calculation. \"\"\" min_score = 0 for item in report.criterion_supplier_score: if item['criterion_id']",
"worst_criterion_score(report, criterion) result = float((best - score) / (best - worst)) return '%.3f'",
"\"\"\" Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w",
"float(get_si_value(report, supplier)) if min_value == 0 or value < min_value: min_value = value",
"index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index):",
"index. \"\"\" total = 0 for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda",
"1 Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report,",
"float(get_si_value(report, supplier)) if value > max_value: max_value = value return '%.4f' % max_value",
"Calculation. \"\"\" si = float(si) ri = float(ri) min_si = float(min_si) max_si =",
"Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report)) result",
"min_value = value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step",
"% total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if value > max_value: max_value",
"criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter( lambda x: x['criterion_id']",
"Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier))",
"report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score: max_score = int(item['score'])",
"or value < min_value: min_value = value return '%.4f' % min_value @register.simple_tag def",
"= float(data['w'][index - 1]) weight = w * float(global_weight(criterion, report)) total += weight",
"worst = worst_criterion_score(report, criterion) result = float((best - score) / (best - worst))",
"str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score']) best = best_criterion_score(report, criterion)",
"criterion) worst = worst_criterion_score(report, criterion) result = float((best - score) / (best -",
"criterion['id'] == column: criterion_index = index break w_value = data['w'][criterion_index] return json.dumps(round(w_value /",
"= float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if score > max_value: max_value = score return",
"= w * float(global_weight(criterion, report)) total += weight return '%.3f' % total @register.simple_tag",
"value = float(get_si_value(report, supplier)) if min_value == 0 or value < min_value: min_value",
"@register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for",
"0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if value > max_value:",
"score return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri,",
"result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation.",
"- score) / (best - worst)) return '%.3f' % result return 0 @register.simple_tag",
"= float(ri) min_si = float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri =",
"= 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score'])",
"cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w",
"1 Calculation. \"\"\" max_value = 0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score(",
"\"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if",
"report): \"\"\" Formula: Global Weight = Criterion W value / Criterion Count For",
"total = 0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion))",
"def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier",
"W value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1]",
"'criterion_%s' % criterion['id'] == column: criterion_index = index break w_value = data['w'][criterion_index] return",
"int(item['score']) > max_score: max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\"",
"\"\"\" max_value = 0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier,",
"== column: criterion_index = index break w_value = data['w'][criterion_index] return json.dumps(round(w_value / criterion_count,",
"Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion,",
"supplier in report.suppliers: value = float(get_si_value(report, supplier)) if min_value == 0 or value",
"Step 1 Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value =",
"item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score: max_score",
"\"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda",
"= value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1",
"in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value == 0 or value <",
"def criterion_w(criterion, report, index): \"\"\" Get W value for given index. \"\"\" data",
"total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score =",
"float(max_ri) total = ((weight * (si - min_si)) / (max_si - min_si)) +",
"- min_ri)) / (max_ri - min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report,",
"= data['w'][criterion_index] return json.dumps(round(w_value / criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\"",
"get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for criterion",
"get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri, si, ri): \"\"\" Vikor Step 1",
"data['main_table'][0]) # get column index from matris for index, column in enumerate(columns): if",
"@register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score = 0",
"matris for index, column in enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index",
"if min_value == 0 or value < min_value: min_value = value return '%.4f'",
"min_ri, max_ri, si, ri): \"\"\" Vikor Step 1 Calculation. \"\"\" si = float(si)",
"> 0: score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion)",
"% result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score",
"def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for",
"Get W value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index -",
"/ (max_ri - min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\"",
"def worst_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" min_score = 0 for",
"+ \\ (((1 - weight) * (ri - min_ri)) / (max_ri - min_ri))",
"in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0 or int(item['score'])",
"max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1",
"\"\"\" min_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and",
"for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score:",
"/ 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index =",
"Step 1 Calculation. \"\"\" max_value = 0 for criterion in report.get_child_criterions(): score =",
"= float(get_si_value(report, supplier)) if min_value == 0 or value < min_value: min_value =",
"result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" max_score =",
"result = float((best - score) / (best - worst)) return '%.3f' % result",
"@register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total = 0",
"\"\"\" max_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if",
"report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score",
"Step 1 Calculation. \"\"\" max_score = 0 for item in report.criterion_supplier_score: if item['criterion_id']",
"@register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W value for given index. \"\"\"",
"/ (best - worst)) return '%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report,",
"= 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if min_value ==",
"given report and index. \"\"\" total = 0 for cr_id, data in report.supplier_compare.items():",
"value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag",
"float(global_weight(criterion, report)) total += weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier,",
"= best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result = float((best - score) /",
"float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total = ((weight * (si -",
"__future__ import division import json from django.template import Library register = Library() def",
"for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def",
"\"\"\" Vikor Step 1 Calculation. \"\"\" min_score = 0 for item in report.criterion_supplier_score:",
"max_value = score return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si,",
"report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x: x != 'criterion_0', data['main_table'][0]) #",
"= 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value ==",
"% result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1",
"given index. \"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report,",
"in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score: max_score =",
"report, index): \"\"\" Get W value for given index. \"\"\" data = report.supplier_compare[str(criterion['id'])]",
"* float(global_weight(criterion, report)) total += weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report,",
"= 0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return",
"\\ int(item['score']) > max_score: max_score = int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier):",
"supplier score for given report and index. \"\"\" total = 0 for cr_id,",
"= 1 / 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])]",
"criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion))",
"value < min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report):",
"0 columns = filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get column index",
"Value = 1 Criterion Count = 5 Global Weight = 1 / 5",
"0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized",
"Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion W value /",
"1]) weight = w * float(global_weight(criterion, report)) total += weight return '%.3f' %",
"report)) total += weight return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion):",
"\"\"\" normalized = float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report)) result =",
"supplier, criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1",
"0.2 \"\"\" criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns =",
"== str(criterion['id']) and \\ int(item['score']) > max_score: max_score = int(item['score']) return max_score @register.simple_tag",
"= int(item['score']) return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation.",
"for given report and index. \"\"\" total = 0 for cr_id, data in",
"0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score ==",
"0 or value < min_value: min_value = value return '%.4f' % min_value @register.simple_tag",
"\"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if",
"1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given report and",
"and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: return result[0]['score'] return 0",
"= float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri = float(max_ri) total =",
"float(min_ri) max_ri = float(max_ri) total = ((weight * (si - min_si)) / (max_si",
"get_min_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier in",
"= 1 Criterion Count = 5 Global Weight = 1 / 5 =",
"def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given report and index. \"\"\"",
"= float((best - score) / (best - worst)) return '%.3f' % result return",
"\"\"\" total = 0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier,",
"return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation.",
"% min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value =",
"Calculation. \"\"\" max_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id'])",
"0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if value > max_value:",
"Calculation. \"\"\" min_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id'])",
"0 for criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f'",
"get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter( lambda",
"* (ri - min_ri)) / (max_ri - min_ri)) return '%.4f' % total @register.simple_tag",
"get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier in",
"Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier in report.suppliers: value",
"= float(global_weight(criterion, report)) result = normalized * w return '%.3f' % result @register.simple_tag",
"min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor",
"'%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value",
"== str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score =",
"def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized = float(get_supplier_normalized_criterion_score(",
"1 Calculation. \"\"\" result = filter( lambda x: x['criterion_id'] == str(criterion['id']) and x['supplier_id']",
"get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total = 0 for criterion",
"worst)) return '%.3f' % result return 0 @register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\"",
"0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if min_value == 0",
"0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step",
"Global Weight = Criterion W value / Criterion Count For example: W Value",
"For example: W Value = 1 Criterion Count = 5 Global Weight =",
"Weight = 1 / 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count'] data =",
"@register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result =",
"item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ (min_score == 0 or",
"return '%.3f' % total @register.simple_tag def get_supplier_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1",
"Calculation. \"\"\" min_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier))",
"if value > max_value: max_value = value return '%.4f' % max_value @register.simple_tag def",
"= 0 columns = filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get column",
"- 1]) weight = w * float(global_weight(criterion, report)) total += weight return '%.3f'",
"report.suppliers: value = float(get_si_value(report, supplier)) if min_value == 0 or value < min_value:",
"= float(get_ri_value(report, supplier)) if min_value == 0 or value < min_value: min_value =",
"list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight =",
"0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if min_value == 0",
"== 0 or value < min_value: min_value = value return '%.4f' % min_value",
"def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0 for supplier",
"import Library register = Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight =",
"for index, column in enumerate(columns): if 'criterion_%s' % criterion['id'] == column: criterion_index =",
"return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"= filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get column index from matris",
"- 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given report",
"max_value = 0 for supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if value",
"= int(result[0]['score']) best = best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result = float((best",
"== str(criterion['id']) and \\ (min_score == 0 or int(item['score']) < min_score): min_score =",
"get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value = 0 for supplier in",
"return '%.4f' % max_value @register.simple_tag def get_qi_value(report, supplier, weight, min_si, max_si, min_ri, max_ri,",
"supplier)) if value > max_value: max_value = value return '%.4f' % max_value @register.simple_tag",
"criterion in report.get_child_criterions(): total += float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total",
"def global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion W value / Criterion",
"float(get_ri_value(report, supplier)) if min_value == 0 or value < min_value: min_value = value",
"> max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_ri_value(report, supplier):",
"max_value @register.simple_tag def get_ri_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value =",
"global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion W value / Criterion Count",
"'criterion_0', data['main_table'][0]) # get column index from matris for index, column in enumerate(columns):",
"from __future__ import division import json from django.template import Library register = Library()",
"float(data['w'][index - 1]) weight = w * float(global_weight(criterion, report)) total += weight return",
"\"\"\" data = report.supplier_compare[str(criterion['id'])] return data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\"",
"1 Calculation. \"\"\" max_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] ==",
"== str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score']) best = best_criterion_score(report,",
"data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w =",
"register = Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion W",
"float((best - score) / (best - worst)) return '%.3f' % result return 0",
"supplier in report.suppliers: value = float(get_ri_value(report, supplier)) if value > max_value: max_value =",
"min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0",
"min_value: min_value = value return '%.4f' % min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor",
"= float(get_ri_value(report, supplier)) if value > max_value: max_value = value return '%.4f' %",
"criterion_count, 4)) @register.simple_tag def criterion_w(criterion, report, index): \"\"\" Get W value for given",
"data['w'][index - 1] @register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given",
"max_ri = float(max_ri) total = ((weight * (si - min_si)) / (max_si -",
"item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score: max_score = int(item['score']) return max_score",
"float(ri) min_si = float(min_si) max_si = float(max_si) min_ri = float(min_ri) max_ri = float(max_ri)",
"Count For example: W Value = 1 Criterion Count = 5 Global Weight",
"min_value @register.simple_tag def get_max_si_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" max_value = 0",
"float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report)) result = normalized * w",
"if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) > max_score: max_score = int(item['score']) return",
"for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0]",
"return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total =",
"= ((weight * (si - min_si)) / (max_si - min_si)) + \\ (((1",
"criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor Step 1 Calculation.",
"criterion_w(criterion, report, index): \"\"\" Get W value for given index. \"\"\" data =",
"0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\ int(item['score']) >",
"\"\"\" max_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and",
"criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1])",
"and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score']) best",
"float(get_supplier_weighted_criterion_score( report, supplier, criterion)) return '%.4f' % total @register.simple_tag def get_min_si_value(report): \"\"\" Vikor",
"min_score = 0 for item in report.criterion_supplier_score: if item['criterion_id'] == str(criterion['id']) and \\",
"x != 'criterion_0', data['main_table'][0]) # get column index from matris for index, column",
"total = 0 for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id'])",
"weight) * (ri - min_ri)) / (max_ri - min_ri)) return '%.4f' % total",
"str(criterion['id']) and \\ (min_score == 0 or int(item['score']) < min_score): min_score = int(item['score'])",
"'%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\" min_value",
"@register.simple_tag def get_supplier_weighted_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" normalized =",
"and \\ (min_score == 0 or int(item['score']) < min_score): min_score = int(item['score']) return",
"in report.supplier_compare.items(): criterion = list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index",
"= criterion['parent']['count'] data = report.criterion_compare[str(criterion['parent']['id'])] criterion_index = 0 columns = filter(lambda x: x",
"@register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result =",
"score for given report and index. \"\"\" total = 0 for cr_id, data",
"max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_min_ri_value(report): \"\"\" Vikor",
"x: x['criterion_id'] == str(criterion['id']) and x['supplier_id'] == str(supplier['id']), report.criterion_supplier_score) if len(result) > 0:",
"'%.3f' % result @register.simple_tag def best_criterion_score(report, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"django.template import Library register = Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight",
"columns = filter(lambda x: x != 'criterion_0', data['main_table'][0]) # get column index from",
"- min_ri)) return '%.4f' % total @register.simple_tag def worst_criterion_score(report, criterion): \"\"\" Vikor Step",
"float(get_ri_value(report, supplier)) if value > max_value: max_value = value return '%.4f' % max_value",
"(si - min_si)) / (max_si - min_si)) + \\ (((1 - weight) *",
"return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor Step 1",
"value / Criterion Count For example: W Value = 1 Criterion Count =",
"division import json from django.template import Library register = Library() def global_weight(criterion, report):",
"if 'criterion_%s' % criterion['id'] == column: criterion_index = index break w_value = data['w'][criterion_index]",
"value > max_value: max_value = value return '%.4f' % max_value @register.simple_tag def get_ri_value(report,",
"= list(filter(lambda x: str(x['id']) == str(cr_id), report.get_child_criterions()))[0] w = float(data['w'][index - 1]) weight",
"= 0 for criterion in report.get_child_criterions(): score = float(get_supplier_weighted_criterion_score( report, supplier, criterion)) if",
"return max_score @register.simple_tag def get_si_value(report, supplier): \"\"\" Vikor Step 1 Calculation. \"\"\" total",
"\\ (((1 - weight) * (ri - min_ri)) / (max_ri - min_ri)) return",
"> 0: return result[0]['score'] return 0 @register.simple_tag def get_supplier_normalized_criterion_score(report, supplier, criterion): \"\"\" Vikor",
"@register.simple_tag def calculate_supplier_score(report, index): \"\"\" Calculate supplier score for given report and index.",
"return '%.4f' % min_value @register.simple_tag def get_max_ri_value(report): \"\"\" Vikor Step 1 Calculation. \"\"\"",
"= float(get_supplier_normalized_criterion_score( report, supplier, criterion)) w = float(global_weight(criterion, report)) result = normalized *",
"max_value = 0 for supplier in report.suppliers: value = float(get_si_value(report, supplier)) if value",
"supplier, criterion): \"\"\" Vikor Step 1 Calculation. \"\"\" result = filter( lambda x:",
"Vikor Step 1 Calculation. \"\"\" max_score = 0 for item in report.criterion_supplier_score: if",
"5 Global Weight = 1 / 5 = 0.2 \"\"\" criterion_count = criterion['parent']['count']",
"Library register = Library() def global_weight(criterion, report): \"\"\" Formula: Global Weight = Criterion",
"best_criterion_score(report, criterion) worst = worst_criterion_score(report, criterion) result = float((best - score) / (best",
"report.criterion_supplier_score) if len(result) > 0: score = int(result[0]['score']) best = best_criterion_score(report, criterion) worst",
"\"\"\" total = 0 for cr_id, data in report.supplier_compare.items(): criterion = list(filter(lambda x:",
"str(criterion['id']) and \\ int(item['score']) > max_score: max_score = int(item['score']) return max_score @register.simple_tag def"
] |
[
"AbstractTrigger from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' +",
"import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK =",
"Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK = Event.RECOMMENDATION_DOWNLOAD_TASK.value",
"src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK",
"RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK = Event.RECOMMENDATION_DOWNLOAD_TASK.value EVENT_ACTION =",
"from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download'",
"class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK = Event.RECOMMENDATION_DOWNLOAD_TASK.value EVENT_ACTION",
"<filename>src/triggers/recommendation_trigger.py from pyframework.triggers.abstract_trigger import AbstractTrigger from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX =",
"from pyframework.triggers.abstract_trigger import AbstractTrigger from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX",
"ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':' + 'download' EVENT_TASK = Event.RECOMMENDATION_DOWNLOAD_TASK.value EVENT_ACTION = Event.RECOMMENDATION_DOWNLOAD_ACTION.value",
"import AbstractTrigger from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX + ':'",
"pyframework.triggers.abstract_trigger import AbstractTrigger from src.commands.fire.base_fire import Event class RecommendationTrigger(AbstractTrigger): ACTION_KEY_PREFIX = AbstractTrigger.ACTION_KEY_PREFIX +"
] |
[
"deserted island where they soon find out they are not alone.'\") #pylint: enable=line-too-long",
"not equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal",
"import datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest):",
"expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After",
"PM', f\"'{show.air_time}' was not equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost:",
"equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to",
"self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}'",
"f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not",
"self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}'",
"'After their plane, Oceanic Air flight 815, tore apart whilst thousands of miles",
"not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal",
"that a show is parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None,",
"rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier,",
"out they are not alone.', f\"'{show.overview}' was not equal to expected overview 'After",
"self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}'",
"deserted island where they soon find out they are not alone.', f\"'{show.overview}' was",
"equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected",
"f\"'{show.aliases}' was not equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}'",
"11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic",
"or equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint:",
"f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was",
"not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not",
"to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was",
"not equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was",
"(US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14',",
"was not equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}'",
"f\"'{show.network}' was not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was",
"'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected identifier '73739'\")",
"not equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to",
"not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28,",
"23, 0, 28, 59), f\"'{show.last_updated}' was not greater or equal to expected last_updated",
"expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal",
"to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected status",
"mysterious deserted island where they soon find out they are not alone.'\") #pylint:",
"plane, Oceanic Air flight 815, tore apart whilst thousands of miles off course,",
"equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal",
"equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59),",
"'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id,",
"not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to",
"site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug,",
"to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal",
"island where they soon find out they are not alone.', f\"'{show.overview}' was not",
"expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day",
"not alone.', f\"'{show.overview}' was not equal to expected overview 'After their plane, Oceanic",
"'{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\")",
"was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal",
"to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id",
"self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}'",
"is parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not",
"11, 23, 0, 28, 59), f\"'{show.last_updated}' was not greater or equal to expected",
"not equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}'",
"Oceanic Air flight 815, tore apart whilst thousands of miles off course, the",
"are not alone.', f\"'{show.overview}' was not equal to expected overview 'After their plane,",
"ShowStatus.ended, f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was",
"was not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama',",
"'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362',",
"def test_show_parse(self): \"\"\"Test that a show is parsed as we'd expect.\"\"\" show =",
"f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not",
"by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time,",
"equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected",
"equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not",
"not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to",
"on a mysterious deserted island where they soon find out they are not",
"expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected added by",
"mysterious deserted island where they soon find out they are not alone.', f\"'{show.overview}'",
"a mysterious deserted island where they soon find out they are not alone.',",
"expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\")",
"73739, f\"'{show.identifier}' was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was",
"equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected",
"to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected rating",
"to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}'",
"to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected site_rating",
"'{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to expected air time '9:00",
"self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM',",
"we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected",
"equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected",
"equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to",
"find themselves on a mysterious deserted island where they soon find out they",
"to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected",
"23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air",
"tore apart whilst thousands of miles off course, the survivors find themselves on",
"'Lost', f\"'{show.name}' was not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}'",
"was not equal to expected overview 'After their plane, Oceanic Air flight 815,",
"equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal",
"to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected series_identifier",
"''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45',",
"they soon find out they are not alone.', f\"'{show.overview}' was not equal to",
"shows.\"\"\" import datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class",
"Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to expected network 'ABC (US)'\")",
"Air flight 815, tore apart whilst thousands of miles off course, the survivors",
"'{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected identifier",
"self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}'",
"59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815, tore",
"not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to",
"to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected runtime",
"greater or equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" )",
"alone.', f\"'{show.overview}' was not equal to expected overview 'After their plane, Oceanic Air",
"from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test",
"show is parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was",
"expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not",
"was not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal",
"equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was",
"ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is parsed as",
"'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC",
"test_show_parse(self): \"\"\"Test that a show is parsed as we'd expect.\"\"\" show = self.client().show_info(73739)",
"Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired,",
"class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is parsed",
"datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\")",
"was not equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'],",
"to expected overview 'After their plane, Oceanic Air flight 815, tore apart whilst",
"their plane, Oceanic Air flight 815, tore apart whilst thousands of miles off",
"0, 28, 59), f\"'{show.last_updated}' was not greater or equal to expected last_updated '{datetime.datetime(2018,",
"not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal",
"equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected",
"survivors find themselves on a mysterious deserted island where they soon find out",
"show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected added 'None'\")",
"whilst thousands of miles off course, the survivors find themselves on a mysterious",
"'24313', f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was",
"first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal",
"was not greater or equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28,",
"of miles off course, the survivors find themselves on a mysterious deserted island",
"#pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815, tore apart whilst",
") #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815, tore apart",
"'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected added by 'None'\") self.assertEqual(show.air_day,",
"not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'],",
"flight 815, tore apart whilst thousands of miles off course, the survivors find",
"show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was not greater or equal",
"expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\")",
"course, the survivors find themselves on a mysterious deserted island where they soon",
"AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}'",
"last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their",
"was not equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not",
"'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00",
"expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\")",
"28, 59), f\"'{show.last_updated}' was not greater or equal to expected last_updated '{datetime.datetime(2018, 11,",
"expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\")",
"'{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to",
"searching for shows.\"\"\" import datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay,",
"f\"'{show.runtime}' was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not",
"import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a",
"site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected slug 'lost\") self.assertEqual(show.status,",
"the survivors find themselves on a mysterious deserted island where they soon find",
"they are not alone.', f\"'{show.overview}' was not equal to expected overview 'After their",
"expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to",
"off course, the survivors find themselves on a mysterious deserted island where they",
"equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to",
"9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected",
"equal to expected overview 'After their plane, Oceanic Air flight 815, tore apart",
"runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating,",
"expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to expected air",
"22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres",
"['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to expected aliases '{['Lost: Missing Pieces']}'\")",
"expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to expected",
"'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was",
"self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to expected aliases '{['Lost: Missing",
"59), f\"'{show.last_updated}' was not greater or equal to expected last_updated '{datetime.datetime(2018, 11, 23,",
"equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected",
"\"\"\"Test searching for shows.\"\"\" import datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import",
"self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}'",
"time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to expected",
"f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not",
"cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is parsed as we'd expect.\"\"\" show",
"import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def",
"f\"'{show.rating}' was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not",
"f\"'{show.added}' was not equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not",
"was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal",
"self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was not greater or",
"'{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated,",
"to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected added",
"tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\"",
"768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was",
"not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to",
"expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected name Lost'\")",
"not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to",
"'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008',",
"to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not",
"'45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1,",
"self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018,",
"22), f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action',",
"'9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost',",
"datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show",
"self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}'",
"zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was not",
"not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal",
"equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected",
"'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\")",
"equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected",
"was not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not",
"'ABC (US)', f\"'{show.network}' was not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '',",
"was not equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal",
"self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004, 9,",
"expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\")",
"overview 'After their plane, Oceanic Air flight 815, tore apart whilst thousands of",
"'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313',",
"self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}'",
"expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected network_identifier",
"'9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to expected aliases",
"was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal",
"'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004,",
"self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}'",
"(US)', f\"'{show.network}' was not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}'",
"equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to",
"\"\"\"Test that a show is parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added,",
"to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to",
"not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to",
"to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to",
"was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal",
"f\"'{show.site_rating_count}' was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not",
"'lost', f\"'{show.slug}' was not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was",
"expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was",
"ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is",
"expected overview 'After their plane, Oceanic Air flight 815, tore apart whilst thousands",
"28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815,",
"was not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal",
"None, f\"'{show.added}' was not equal to expected added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was",
"expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected rating 'TV-14'\")",
"'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres '{['Action', 'Adventure', 'Drama',",
"self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815, tore apart whilst thousands of",
"not equal to expected overview 'After their plane, Oceanic Air flight 815, tore",
"None, f\"'{show.added_by}' was not equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}'",
"self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres '{['Action',",
"f\"'{show.identifier}' was not equal to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not",
"expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected",
"from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test",
"was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was",
"f\"'{show.last_updated}' was not greater or equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0,",
"thousands of miles off course, the survivors find themselves on a mysterious deserted",
"was not equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was",
"was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal",
"to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected slug",
"'45', f\"'{show.runtime}' was not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was",
"self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}'",
"not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to",
"aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner",
"where they soon find out they are not alone.', f\"'{show.overview}' was not equal",
"AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show",
"self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9,",
"series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count,",
"to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected",
"not equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not",
"not equal to expected runtime '45'\") self.assertEqual(show.series_identifier, '24313', f\"'{show.series_identifier}' was not equal to",
"equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}'",
"imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected name Lost'\") self.assertEqual(show.network,",
"'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11,",
"added 'None'\") self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected added by 'None'\")",
"Missing Pieces'], f\"'{show.aliases}' was not equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner,",
"identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name,",
"PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to expected aliases '{['Lost:",
"miles off course, the survivors find themselves on a mysterious deserted island where",
"as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to",
"themselves on a mysterious deserted island where they soon find out they are",
"equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long",
"self.assertEqual(show.added_by, None, f\"'{show.added_by}' was not equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday,",
"air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to expected air time",
"['Action', 'Adventure', 'Drama', 'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres '{['Action', 'Adventure',",
"a mysterious deserted island where they soon find out they are not alone.'\")",
"to expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id",
"f\"'{show.network_identifier}' was not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not",
"'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22),",
"to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to expected",
"to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to expected",
"was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal",
"equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected",
"soon find out they are not alone.', f\"'{show.overview}' was not equal to expected",
"expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to expected network",
"was not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal",
"'{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane,",
"disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight 815, tore apart whilst thousands",
"banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}' was not equal to expected first_aired",
"to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected name",
"f\"'{show.overview}' was not equal to expected overview 'After their plane, Oceanic Air flight",
"was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal",
"self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier,",
"9, 22), f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres,",
"f\"'{show.air_time}' was not equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing",
"expected identifier '73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\")",
"self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not equal to expected air time '9:00 PM'\")",
"= self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected added 'None'\") self.assertEqual(show.added_by,",
"'TV-14', f\"'{show.rating}' was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was",
"'73739'\") self.assertEqual(show.imdb_id, 'tt0411008', f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost',",
"'24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768,",
"f\"'{show.name}' was not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was",
"test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is parsed as we'd expect.\"\"\"",
"f\"'{show.added_by}' was not equal to expected added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was",
"name Lost'\") self.assertEqual(show.network, 'ABC (US)', f\"'{show.network}' was not equal to expected network 'ABC",
"status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id, 'SH672362', f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual(",
"equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected",
"'', f\"'{show.network_identifier}' was not equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was",
"network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected network_identifier ''\")",
"was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0,",
"f\"'{show.imdb_id}' was not equal to expected imdb_id 'tt0411008'\") self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not",
"air time '9:00 PM'\") self.assertEqual(show.aliases, ['Lost: Missing Pieces'], f\"'{show.aliases}' was not equal to",
"slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not equal to expected status '{ShowStatus.ended}'\") self.assertEqual(show.zap2it_id,",
"for shows.\"\"\" import datetime from tests.context import BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus",
"self.assertEqual(show.name, 'Lost', f\"'{show.name}' was not equal to expected name Lost'\") self.assertEqual(show.network, 'ABC (US)',",
"was not equal to expected network 'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not",
"'768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended,",
"'Science-Fiction'], f\"'{show.genres}' was not equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier,",
"to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview,",
"not equal to expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to",
"f\"'{show.first_aired}' was not equal to expected first_aired '{datetime.date(2004, 9, 22)}'\") self.assertEqual(show.genres, ['Action', 'Adventure',",
"parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal",
"'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was not greater",
"self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected added 'None'\") self.assertEqual(show.added_by, None,",
"expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}' was not equal to expected added",
"genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739, f\"'{show.identifier}' was not equal to expected",
"added by 'None'\") self.assertEqual(show.air_day, AirDay.tuesday, f\"'{show.air_day}' was not equal to expected air_day '{AirDay.tuesday}'\")",
"datetime.datetime(2018, 11, 23, 0, 28, 59), f\"'{show.last_updated}' was not greater or equal to",
"not equal to expected series_identifier '24313'\") self.assertEqual(show.site_rating, 9.1, f\"'{show.site_rating}' was not equal to",
"a show is parsed as we'd expect.\"\"\" show = self.client().show_info(73739) self.assertEqual(show.added, None, f\"'{show.added}'",
"find out they are not alone.', f\"'{show.overview}' was not equal to expected overview",
"f\"'{show.genres}' was not equal to expected genres '{['Action', 'Adventure', 'Drama', 'Science-Fiction']}'\") self.assertEqual(show.identifier, 73739,",
"expected site_rating_count '768'\") self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected slug 'lost\")",
"self.assertEqual(show.slug, 'lost', f\"'{show.slug}' was not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}'",
"0, 28, 59)}'\" ) #pylint: disable=line-too-long self.assertEqual(show.overview, 'After their plane, Oceanic Air flight",
"'ABC (US)'\") self.assertEqual(show.network_identifier, '', f\"'{show.network_identifier}' was not equal to expected network_identifier ''\") self.assertEqual(show.rating,",
"BaseTVDBTest from libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self):",
"'9:00 PM', f\"'{show.air_time}' was not equal to expected air time '9:00 PM'\") self.assertEqual(show.aliases,",
"not greater or equal to expected last_updated '{datetime.datetime(2018, 11, 23, 0, 28, 59)}'\"",
"was not equal to expected air_day '{AirDay.tuesday}'\") self.assertEqual(show.air_time, '9:00 PM', f\"'{show.air_time}' was not",
"network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected rating 'TV-14'\") self.assertEqual(show.runtime,",
"to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was not equal to expected site_rating_count",
"apart whilst thousands of miles off course, the survivors find themselves on a",
"\"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that a show is parsed as we'd",
"Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg', f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004,",
"815, tore apart whilst thousands of miles off course, the survivors find themselves",
"f\"'{show.zap2it_id}' was not equal to expected zap2it_id 'SH672362'\") self.assertGreaterEqual( show.last_updated, datetime.datetime(2018, 11, 23,",
"Pieces'], f\"'{show.aliases}' was not equal to expected aliases '{['Lost: Missing Pieces']}'\") self.assertEqual(show.banner, 'graphical/73739-g4.jpg',",
"libtvdb.model.enums import AirDay, ShowStatus class ShowTestSuite(BaseTVDBTest): \"\"\"Show test cases.\"\"\" def test_show_parse(self): \"\"\"Test that",
"f\"'{show.banner}' was not equal to expected banner 'graphical/73739-g4.jpg\") self.assertEqual(show.first_aired, datetime.date(2004, 9, 22), f\"'{show.first_aired}'",
"expected rating 'TV-14'\") self.assertEqual(show.runtime, '45', f\"'{show.runtime}' was not equal to expected runtime '45'\")",
"f\"'{show.slug}' was not equal to expected slug 'lost\") self.assertEqual(show.status, ShowStatus.ended, f\"'{show.status}' was not",
"equal to expected network_identifier ''\") self.assertEqual(show.rating, 'TV-14', f\"'{show.rating}' was not equal to expected",
"9.1, f\"'{show.site_rating}' was not equal to expected site_rating '9.1'\") self.assertEqual(show.site_rating_count, 768, f\"'{show.site_rating_count}' was"
] |
[
"args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def config(cls, config,",
"Fake data sources used for testing \"\"\" import asyncio from typing import Any,",
"if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo in self.config.repos} @classmethod def",
"self.mem = {repo.src_url: repo for repo in self.config.repos} @classmethod def args(cls, args, *above)",
"from typing import Any, Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig from",
"= repo async def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo",
"class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self) ->",
"async def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async def",
"Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo import Repo from",
"BaseConfig from ..repo import Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg import",
"repo): self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values():",
"from ..base import BaseConfig from ..repo import Repo from .source import BaseSourceContext, BaseSource",
"repo in self.parent.mem.values(): yield repo async def repo(self, src_url: str) -> Repo: return",
"async def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple):",
") return args @classmethod def config(cls, config, *above): return MemorySourceConfig( repos=list(map(Repo, cls.config_get(config, above,",
"Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo in",
"BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def",
"str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class",
"import BaseConfig from ..repo import Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg",
"in self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args, above,",
"Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def",
"for repo in self.parent.mem.values(): yield repo async def repo(self, src_url: str) -> Repo:",
"MIT # Copyright (c) 2019 Intel Corporation \"\"\" Fake data sources used for",
"sources used for testing \"\"\" import asyncio from typing import Any, Dict, List,",
"async def update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]: for",
"..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo async",
"def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async def repo(self,",
"testing \"\"\" import asyncio from typing import Any, Dict, List, NamedTuple, AsyncIterator from",
"List, NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo import Repo from .source",
"<filename>dffml/source/memory.py<gh_stars>0 # SPDX-License-Identifier: MIT # Copyright (c) 2019 Intel Corporation \"\"\" Fake data",
"2019 Intel Corporation \"\"\" Fake data sources used for testing \"\"\" import asyncio",
"import asyncio from typing import Any, Dict, List, NamedTuple, AsyncIterator from ..base import",
"yield repo async def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class",
"data sources used for testing \"\"\" import asyncio from typing import Any, Dict,",
"-> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async def repo(self, src_url: str)",
"in a dict in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig)",
"self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for",
"entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self)",
"Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod",
"List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a dict in memory \"\"\"",
"used for testing \"\"\" import asyncio from typing import Any, Dict, List, NamedTuple,",
"super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo",
"CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo]",
"args, *above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) )",
"above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def config(cls, config, *above):",
"__init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config,",
"def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\",",
"@classmethod def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str,",
"Copyright (c) 2019 Intel Corporation \"\"\" Fake data sources used for testing \"\"\"",
"Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in",
"..util.cli.arg import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo):",
"dict in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) -> None:",
"Stores repos in a dict in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self,",
"import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext):",
"args @classmethod def config(cls, config, *above): return MemorySourceConfig( repos=list(map(Repo, cls.config_get(config, above, \"keys\"))) )",
"self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield",
"BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async",
"\"\"\" import asyncio from typing import Any, Dict, List, NamedTuple, AsyncIterator from ..base",
"def update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]: for repo",
"-> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource):",
"-> None: super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem =",
"Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\"",
".source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import entry_point class",
"in self.parent.mem.values(): yield repo async def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url,",
"return args @classmethod def config(cls, config, *above): return MemorySourceConfig( repos=list(map(Repo, cls.config_get(config, above, \"keys\")))",
"repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a dict in memory",
"nargs=\"+\", default=[]) ) return args @classmethod def config(cls, config, *above): return MemorySourceConfig( repos=list(map(Repo,",
"import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url]",
"..base import BaseConfig from ..repo import Repo from .source import BaseSourceContext, BaseSource from",
"NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a dict in",
"BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem",
"asyncio from typing import Any, Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig",
"cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def config(cls,",
"MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a dict",
"# Copyright (c) 2019 Intel Corporation \"\"\" Fake data sources used for testing",
"repo async def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig,",
"isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo in self.config.repos} @classmethod def args(cls,",
"import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo async def",
"= {repo.src_url: repo for repo in self.config.repos} @classmethod def args(cls, args, *above) ->",
"Corporation \"\"\" Fake data sources used for testing \"\"\" import asyncio from typing",
"Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import",
"def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] = {} if",
"self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos",
"*above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return",
"Any, Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo import Repo",
"memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem:",
"MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]:",
"from ..util.cli.arg import Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self,",
"for testing \"\"\" import asyncio from typing import Any, Dict, List, NamedTuple, AsyncIterator",
"class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a",
"repos in a dict in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config:",
"repo async def repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async",
"\"\"\" Fake data sources used for testing \"\"\" import asyncio from typing import",
"\"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def config(cls, config, *above): return",
"NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo import Repo from .source import",
"from ..repo import Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg",
"MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] = {}",
"config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig):",
"AsyncIterator from ..base import BaseConfig from ..repo import Repo from .source import BaseSourceContext,",
"Arg(type=str, nargs=\"+\", default=[]) ) return args @classmethod def config(cls, config, *above): return MemorySourceConfig(",
"update(self, repo): self.parent.mem[repo.src_url] = repo async def repos(self) -> AsyncIterator[Repo]: for repo in",
"(c) 2019 Intel Corporation \"\"\" Fake data sources used for testing \"\"\" import",
"repo for repo in self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str, Arg]:",
"return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores",
"MemorySource(BaseSource): \"\"\" Stores repos in a dict in memory \"\"\" CONTEXT = MemorySourceContext",
"import Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint",
"\"\"\" Stores repos in a dict in memory \"\"\" CONTEXT = MemorySourceContext def",
"{} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo in self.config.repos} @classmethod",
"None: super().__init__(config) self.mem: Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url:",
"for repo in self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set(",
"Dict[str, Repo] = {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo",
"-> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[]) ) return args",
"repo in self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args,",
"@entry_point(\"memory\") class MemorySource(BaseSource): \"\"\" Stores repos in a dict in memory \"\"\" CONTEXT",
"# SPDX-License-Identifier: MIT # Copyright (c) 2019 Intel Corporation \"\"\" Fake data sources",
"repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo]",
"class MemorySource(BaseSource): \"\"\" Stores repos in a dict in memory \"\"\" CONTEXT =",
"default=[]) ) return args @classmethod def config(cls, config, *above): return MemorySourceConfig( repos=list(map(Repo, cls.config_get(config,",
"typing import Any, Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo",
"SPDX-License-Identifier: MIT # Copyright (c) 2019 Intel Corporation \"\"\" Fake data sources used",
"Intel Corporation \"\"\" Fake data sources used for testing \"\"\" import asyncio from",
"repos(self) -> AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async def repo(self, src_url:",
"import Any, Dict, List, NamedTuple, AsyncIterator from ..base import BaseConfig from ..repo import",
"MemorySourceConfig): self.mem = {repo.src_url: repo for repo in self.config.repos} @classmethod def args(cls, args,",
"Arg from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] =",
"args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\", Arg(type=str, nargs=\"+\", default=[])",
"= {} if isinstance(self.config, MemorySourceConfig): self.mem = {repo.src_url: repo for repo in self.config.repos}",
"= MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str, Repo] =",
"a dict in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) ->",
"\"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config) self.mem: Dict[str,",
"in memory \"\"\" CONTEXT = MemorySourceContext def __init__(self, config: BaseConfig) -> None: super().__init__(config)",
"{repo.src_url: repo for repo in self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str,",
"self.parent.mem.values(): yield repo async def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url))",
"AsyncIterator[Repo]: for repo in self.parent.mem.values(): yield repo async def repo(self, src_url: str) ->",
"self.config.repos} @classmethod def args(cls, args, *above) -> Dict[str, Arg]: cls.config_set( args, above, \"keys\",",
"src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos: List[Repo] @entry_point(\"memory\")",
"from ..util.entrypoint import entry_point class MemorySourceContext(BaseSourceContext): async def update(self, repo): self.parent.mem[repo.src_url] = repo",
"..repo import Repo from .source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from",
"from .source import BaseSourceContext, BaseSource from ..util.cli.arg import Arg from ..util.entrypoint import entry_point",
"def repo(self, src_url: str) -> Repo: return self.parent.mem.get(src_url, Repo(src_url)) class MemorySourceConfig(BaseConfig, NamedTuple): repos:"
] |
[
"\"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom =",
"self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 )",
"'nv_cost', 'week_of_month'] # Cell import gpytorch from math import ceil import datetime #",
"edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell",
"= self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def",
"MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module =",
"def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) #",
"return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu, co): if q>y: cost",
"super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x):",
"super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel(",
"dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom",
"nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import",
"train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks",
"cost = (q-y)*co else: cost = (y-q)*cu return cost # Cell def week_of_month(dt_str):",
"Cell def week_of_month(dt_str): \"\"\" Returns the week of the month for the specified",
"covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x,",
"first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + first_day.weekday() return int(ceil(adjusted_dom/7.0))",
"gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)",
"import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood):",
"import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x,",
"the month for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day =",
"if q>y: cost = (q-y)*co else: cost = (y-q)*cu return cost # Cell",
"def nv_cost(q, y, cu, co): if q>y: cost = (q-y)*co else: cost =",
"self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x",
"mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP):",
"train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks )",
"= gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x =",
"likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self,",
"the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom =",
"gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu, co): if q>y: cost =",
"self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self,",
"datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + first_day.weekday()",
"cost = (y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\" Returns the week",
"def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module",
"AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ =",
"= gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def",
"self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x = self.mean_module(x)",
"y, cu, co): if q>y: cost = (q-y)*co else: cost = (y-q)*cu return",
"date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom",
"train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x =",
"x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def",
"def week_of_month(dt_str): \"\"\" Returns the week of the month for the specified date.",
"q>y: cost = (q-y)*co else: cost = (y-q)*cu return cost # Cell def",
"from math import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x,",
"= (q-y)*co else: cost = (y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\"",
"num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module =",
"= self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y,",
"ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel,",
"# Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y,",
"def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean(",
"import gpytorch from math import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def",
"train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def",
"gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x = self.mean_module(x) covar_x =",
"= gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x,",
"EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost',",
"'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from math import ceil import datetime",
"= gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x = self.mean_module(x) covar_x",
"likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1",
"otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from",
"class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module =",
"= self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu, co): if",
"gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x)",
"mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q,",
"cost # Cell def week_of_month(dt_str): \"\"\" Returns the week of the month for",
"of the month for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day",
"__init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(),",
"= self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y,",
"['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from math import ceil import",
"self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu, co): if q>y:",
"forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell",
"= ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from math import ceil",
") self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x =",
"specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from math",
"week of the month for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d')",
"likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module",
"datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y,",
"def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) #",
"gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x)",
"Cell def nv_cost(q, y, cu, co): if q>y: cost = (q-y)*co else: cost",
"nv_cost(q, y, cu, co): if q>y: cost = (q-y)*co else: cost = (y-q)*cu",
"cu, co): if q>y: cost = (q-y)*co else: cost = (y-q)*cu return cost",
"File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month']",
"num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return",
"# Cell import gpytorch from math import ceil import datetime # Cell class",
"forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell",
"the week of the month for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str,",
"= (y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\" Returns the week of",
"'week_of_month'] # Cell import gpytorch from math import ceil import datetime # Cell",
"gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self,",
"train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel())",
"for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom",
"specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day",
"covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x,",
"self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return",
"Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood)",
"co): if q>y: cost = (q-y)*co else: cost = (y-q)*cu return cost #",
"gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x):",
") def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x)",
"return cost # Cell def week_of_month(dt_str): \"\"\" Returns the week of the month",
"__init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module =",
"num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks, rank=1 ) def forward(self, x): mean_x",
"= datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom +",
"Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module",
"self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu,",
"x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class",
"'%Y-%m-%d') first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + first_day.weekday() return",
"return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks):",
"DO NOT EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel',",
"gpytorch from math import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self,",
"else: cost = (y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\" Returns the",
"(q-y)*co else: cost = (y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\" Returns",
"self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x) covar_x",
"# Cell def nv_cost(q, y, cu, co): if q>y: cost = (q-y)*co else:",
"self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(),",
"covar_x) # Cell def nv_cost(q, y, cu, co): if q>y: cost = (q-y)*co",
"(y-q)*cu return cost # Cell def week_of_month(dt_str): \"\"\" Returns the week of the",
"# Cell def week_of_month(dt_str): \"\"\" Returns the week of the month for the",
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__",
"class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module",
"train_y, likelihood) self.mean_module = gpytorch.means.MultitaskMean( gpytorch.means.ConstantMean(), num_tasks=num_tasks ) self.covar_module = gpytorch.kernels.MultitaskKernel( gpytorch.kernels.RBFKernel(), num_tasks=num_tasks,",
"self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood,",
"covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x) # Cell def nv_cost(q, y, cu, co):",
"\"\"\" Returns the week of the month for the specified date. \"\"\" dt",
"NOT EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel',",
"month for the specified date. \"\"\" dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d') first_day = dt.replace(day=1)",
"(unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch",
"ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean()",
"__all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] # Cell import gpytorch from math import",
"Returns the week of the month for the specified date. \"\"\" dt =",
"# Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(ExactGPModel, self).__init__(train_x, train_y, likelihood)",
"gpytorch.distributions.MultivariateNormal(mean_x, covar_x) # Cell class MultitaskGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, num_tasks): super(MultitaskGPModel,",
"math import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y,",
"to edit: nbs/00_core.ipynb (unless otherwise specified). __all__ = ['ExactGPModel', 'MultitaskGPModel', 'nv_cost', 'week_of_month'] #",
"Cell import gpytorch from math import ceil import datetime # Cell class ExactGPModel(gpytorch.models.ExactGP):",
"week_of_month(dt_str): \"\"\" Returns the week of the month for the specified date. \"\"\"",
"likelihood) self.mean_module = gpytorch.means.ConstantMean() self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.PeriodicKernel()) def forward(self, x): mean_x = self.mean_module(x)",
"rank=1 ) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultitaskMultivariateNormal(mean_x,"
] |
[] |
[
"get the necessary stats on the words word2number_of_pages_having_it = {} # e.g. 'word'",
"page = self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page): # mark the",
"sorts the results by TF.IDF importance of the search phrase in the page",
"given text file, and makes pages out of it\"\"\" with open(fname, 'r') as",
"in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get max-word frequency for",
"following pages (sorted by importance): \") for pas in pages_and_scores: print(\"\\tPage \" +",
"print() def print_all(self, width=120): \"\"\"Prints all the pages of the book, one by",
"in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the",
"for the text in all the pages, then sorts the results by TF.IDF",
"page_number, k=10): \"\"\"Gets the top k important words for given page\"\"\" words_and_importances =",
"str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index):",
"page2word_frequency[i][word] += 1 # if this is the first time we see this",
"def print_all(self, width=120): \"\"\"Prints all the pages of the book, one by one,",
"print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the pages of the book, one",
"words word = self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0: continue yield",
"phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf",
"\" + str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] +",
"for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not",
"-> '15' page2word_frequency = {} # e.g. 47 -> ('word' -> 2) for",
"if not c.isalpha(): continue filtered += c return filtered def __split_to_words(self, s): \"\"\"Splits",
"{} for word in self.__split_to_words(page): # mark the occurence of the word for",
"b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10) if __name__ == '__main__':",
"book, one by one, to the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width)",
"fname, lines_per_page=20): \"\"\"Opens given text file, and makes pages out of it\"\"\" with",
"# Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" -",
"words found in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod",
"pages containing the text found_pages = [i for i in range(len(self._pages)) if text",
"# sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" +",
"f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for given word\"\"\" if not self.can_do_tfidf:",
"text found_pages = [i for i in range(len(self._pages)) if text in self._pages[i]] #",
"= False if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True",
"'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import math # ---------------------------------------------------------------",
"for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance = \"",
"0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def",
"not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] += 1 #",
"def save_to_file(self, fname): \"\"\"Saves the book to a specified file\"\"\" with open(fname, 'wb')",
"--------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" - one can add pages, save/load",
"--------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf",
"to the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10):",
"+= c return filtered def __split_to_words(self, s): \"\"\"Splits the string s to words",
"-> 17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency",
"in all the pages, then sorts the results by TF.IDF importance of the",
"\" + str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self,",
"= \"\" for c in word: if not c.isalpha(): continue filtered += c",
"# Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page to the",
"= None self._page2word_frequency = None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface #",
"this page first_occurence = False if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0",
"False if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word]",
"\\\"\" + text + \"\\\" located in following pages (sorted by importance): \")",
"filtered = \"\" for c in word: if not c.isalpha(): continue filtered +=",
"# get max-word frequency for each page page2max_word_frequency = {} # e.g. 47",
"page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word",
"e.g. 47 -> ('word' -> 2) for i in range(len(self._pages)): page = self._pages[i]",
"Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" - one can add",
"# of pages having it if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word]",
"to a specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self,",
"word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not in self._word2number_of_pages_having_it",
"words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on page \"",
"frequency for each page page2max_word_frequency = {} # e.g. 47 -> 17 for",
"\"\"\" # find pages containing the text found_pages = [i for i in",
"pages_and_scores = [] for i in found_pages: score = 0 for word in",
"TF.IDF\"\"\" # get the necessary stats on the words word2number_of_pages_having_it = {} #",
"if len(line) == width: print(line) line = \"\" print(line) print('-'*width) print() def print_all(self,",
"i) pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search",
"each page page2max_word_frequency = {} # e.g. 47 -> 17 for i in",
"False def search_for(self, text): \"\"\"Searches for the text in all the pages, then",
"stats necessary for computation of TF.IDF\"\"\" # get the necessary stats on the",
"# --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None",
"\" (importance = \" + str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation #",
"[] for line in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if",
"in found_pages: score = 0 for word in words: score += self.__tf_idf(word, i)",
"the words word2number_of_pages_having_it = {} # e.g. 'word' -> '15' page2word_frequency = {}",
"for each found page pages_and_scores = [] for i in found_pages: score =",
"wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance = \" + str(wai[1])",
"words on page \" + str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\"",
"\"\"\"Splits the string s to words (in a simplistic manner used in this",
"all the pages, then sorts the results by TF.IDF importance of the search",
"print(\"| Page \" + str(page_number + 1)) print('-'*width) line = \"\" for c",
"self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF for given",
"Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10) if __name__ ==",
"as f: lines = f.readlines() buffer = [] for line in lines: buffer.append(line)",
"= pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints the specified page",
"in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance score",
"# skip empty words word = self.__filter_to_letters(word) word = word.lower() if len(word.strip()) ==",
"if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] +=",
"for i in found_pages: score = 0 for word in words: score +=",
"from specified file\"\"\" with open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf =",
"load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\" with open(fname, 'rb') as f:",
"file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the",
"def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given word on given page\"\"\"",
"= max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf =",
"{} # e.g. 47 -> ('word' -> 2) for i in range(len(self._pages)): page",
"= page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main():",
"main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10)",
"words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda",
"math # --------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents an",
"# --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- #",
"self.__compute_stats_for_tfidf() f = 0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index]",
"else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of",
"to words words = [word for word in self.__split_to_words(text)] # get the importance-score",
"word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words",
"the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text",
"+ \")\") def save_to_file(self, fname): \"\"\"Saves the book to a specified file\"\"\" with",
"see this word for this page, we also increase the # of pages",
"= 0 word2number_of_pages_having_it[word] += 1 # get max-word frequency for each page page2max_word_frequency",
"page page2max_word_frequency = {} # e.g. 47 -> 17 for i in page2word_frequency:",
"str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance",
"# Main # --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\")",
"computation of TF.IDF\"\"\" # get the necessary stats on the words word2number_of_pages_having_it =",
"search phrase in the page \"\"\" # find pages containing the text found_pages",
"{} # e.g. 'word' -> '15' page2word_frequency = {} # e.g. 47 ->",
"word2number_of_pages_having_it = {} # e.g. 'word' -> '15' page2word_frequency = {} # e.g.",
"not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word]",
"# --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point",
"= 'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import math #",
"words (in a simplistic manner used in this class) and iterates through them\"\"\"",
"in range(len(self._pages)) if text in self._pages[i]] # split the search string to words",
"we also increase the # of pages having it if first_occurence: if word",
"line = \"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the pages",
"manner used in this class) and iterates through them\"\"\" for word in s.split('",
"word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance",
"self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for the text in all the",
"c.isalpha(): continue filtered += c return filtered def __split_to_words(self, s): \"\"\"Splits the string",
"found_pages = [i for i in range(len(self._pages)) if text in self._pages[i]] # split",
"for word in self.__split_to_words(page): # mark the occurence of the word for this",
"= {} for word in self.__split_to_words(page): # mark the occurence of the word",
"for word in self.__split_to_words(text)] # get the importance-score for each found page pages_and_scores",
"f: lines = f.readlines() buffer = [] for line in lines: buffer.append(line) if",
"__split_to_words(self, s): \"\"\"Splits the string s to words (in a simplistic manner used",
"= False def search_for(self, text): \"\"\"Searches for the text in all the pages,",
"def print_page(self, page_number, width=120): \"\"\"Prints the specified page of the book, to the",
"== width: print(line) line = \"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints",
"the book, to the console One may specify the maximum width of the",
"--------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of",
"pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\" with open(fname,",
"\"\"\"Computes the IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0",
"all the pages of the book, one by one, to the console\"\"\" for",
"for each page page2max_word_frequency = {} # e.g. 47 -> 17 for i",
"page2word_frequency = {} # e.g. 47 -> ('word' -> 2) for i in",
"= {} # e.g. 'word' -> '15' page2word_frequency = {} # e.g. 47",
"each found page pages_and_scores = [] for i in found_pages: score = 0",
"return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to contain letters only\"\"\"",
"one, to the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number,",
"stats on the words word2number_of_pages_having_it = {} # e.g. 'word' -> '15' page2word_frequency",
"first_occurence = True page2word_frequency[i][word] += 1 # if this is the first time",
"with open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self,",
"this class) and iterates through them\"\"\" for word in s.split(' '): # skip",
"the TF.IDF for given word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return",
"else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for given word\"\"\"",
"self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True #",
"def __get_words_for_page(self, page_index): \"\"\"Gets the set of words found in the given page\"\"\"",
"text): \"\"\"Searches for the text in all the pages, then sorts the results",
"word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self,",
"in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for",
"page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] += 1 # if this is",
"if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not in self._page2word_frequency[page_index] else",
"page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main # ---------------------------------------------------------------",
"words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1],",
"line += c if len(line) == width: print(line) line = \"\" print(line) print('-'*width)",
"it\"\"\" with open(fname, 'r') as f: lines = f.readlines() buffer = [] for",
"to contain letters only\"\"\" filtered = \"\" for c in word: if not",
"word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- #",
"reverse=True) print(\"Search phrase \\\"\" + text + \"\\\" located in following pages (sorted",
"book\" - one can add pages, save/load to file and search for phrases\"\"\"",
"Book: \"\"\"Represents an \"electronic book\" - one can add pages, save/load to file",
"False def print_page(self, page_number, width=120): \"\"\"Prints the specified page of the book, to",
"self._pages[page_number]: line += c if len(line) == width: print(line) line = \"\" print(line)",
"self.__compute_stats_for_tfidf() n_word = 0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1",
"page \"\"\" # find pages containing the text found_pages = [i for i",
"specified file\"\"\" with open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf = False",
"not c.isalpha(): continue filtered += c return filtered def __split_to_words(self, s): \"\"\"Splits the",
"the book, one by one, to the console\"\"\" for i in range(len(self._pages)): self.print_page(i,",
"n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of words found in the given",
"buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches",
"words for given page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word,",
"given word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def",
"'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120):",
"\"\"\"Computes the TF.IDF for given word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf()",
"--------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page to",
"= Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10) if __name__",
"self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface",
"open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number,",
"of TF.IDF\"\"\" # get the necessary stats on the words word2number_of_pages_having_it = {}",
"pages out of it\"\"\" with open(fname, 'r') as f: lines = f.readlines() buffer",
"found in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def",
"[i for i in range(len(self._pages)) if text in self._pages[i]] # split the search",
"page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] += 1 # if this",
"# e.g. 47 -> 17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it",
"1)) print('-'*width) line = \"\" for c in self._pages[page_number]: line += c if",
"to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given",
"= word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # ---------------------------------------------------------------",
"containing the text found_pages = [i for i in range(len(self._pages)) if text in",
"one can add pages, save/load to file and search for phrases\"\"\" # ---------------------------------------------------------------",
"c return filtered def __split_to_words(self, s): \"\"\"Splits the string s to words (in",
"True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt')",
"word filtered to contain letters only\"\"\" filtered = \"\" for c in word:",
"word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the",
"continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\" #",
"[] for i in found_pages: score = 0 for word in words: score",
"page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on page \" + str(page_number",
"class) and iterates through them\"\"\" for word in s.split(' '): # skip empty",
"if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get",
"\"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the pages of the",
"the word filtered to contain letters only\"\"\" filtered = \"\" for c in",
"def __init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency =",
"in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top k important",
"[] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most",
"= f.readlines() buffer = [] for line in lines: buffer.append(line) if len(buffer) ==",
"+ 1)) print('-'*width) line = \"\" for c in self._pages[page_number]: line += c",
"on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word,",
"score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda x:",
"page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf",
"return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of words found",
"= False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and makes pages",
"# Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given",
"\"\" for c in word: if not c.isalpha(): continue filtered += c return",
"in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] += 1 # if",
"yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\" # get",
"book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file,",
"to file and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def",
"text in self._pages[i]] # split the search string to words words = [word",
"letters only\"\"\" filtered = \"\" for c in word: if not c.isalpha(): continue",
"pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance = \" +",
"buffer = [] for line in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer))",
"the pages, then sorts the results by TF.IDF importance of the search phrase",
"{} # e.g. 47 -> 17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values())",
"self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency",
"= \" + str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the book to",
"= [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True)",
"= \" + str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def",
"string s to words (in a simplistic manner used in this class) and",
"= {} # e.g. 47 -> ('word' -> 2) for i in range(len(self._pages)):",
"+ text + \"\\\" located in following pages (sorted by importance): \") for",
"the page \"\"\" print('-'*width) print(\"| Page \" + str(page_number + 1)) print('-'*width) line",
"\"\\\" located in following pages (sorted by importance): \") for pas in pages_and_scores:",
"save_to_file(self, fname): \"\"\"Saves the book to a specified file\"\"\" with open(fname, 'wb') as",
"reverse=True) print(\"Most important words on page \" + str(page_number + 1)) for wai",
"string to words words = [word for word in self.__split_to_words(text)] # get the",
"for given page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number)))",
"print(\"Most important words on page \" + str(page_number + 1)) for wai in",
"\"\"\"Returns the word filtered to contain letters only\"\"\" filtered = \"\" for c",
"pages (sorted by importance): \") for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0])",
"lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer))",
"= 0 for word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) #",
"len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation",
"\"\"\"Computes stats necessary for computation of TF.IDF\"\"\" # get the necessary stats on",
"if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1",
"search string to words words = [word for word in self.__split_to_words(text)] # get",
"line in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) !=",
"i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top k",
"\"\"\"Computes the TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0",
"+= 1 # get max-word frequency for each page page2max_word_frequency = {} #",
"in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance = \" + str(pas[1])",
"# --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page",
"the string s to words (in a simplistic manner used in this class)",
"('word' -> 2) for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {}",
"occurence of the word for this page first_occurence = False if word not",
"--------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0)",
"the text found_pages = [i for i in range(len(self._pages)) if text in self._pages[i]]",
"+ str(page_number + 1)) print('-'*width) line = \"\" for c in self._pages[page_number]: line",
"\")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the",
"for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important",
"filtered def __split_to_words(self, s): \"\"\"Splits the string s to words (in a simplistic",
"book to a specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f) def",
"on page \" + str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\" +",
"necessary stats on the words word2number_of_pages_having_it = {} # e.g. 'word' -> '15'",
"first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 #",
"i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency",
"47 -> 17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it",
"__init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency = None",
"word): \"\"\"Computes the IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word =",
"IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word",
"# e.g. 'word' -> '15' page2word_frequency = {} # e.g. 47 -> ('word'",
"__tf(self, word, page_index): \"\"\"Computes the TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf()",
"\"\" for c in self._pages[page_number]: line += c if len(line) == width: print(line)",
"page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes",
"if text in self._pages[i]] # split the search string to words words =",
"importance of the search phrase in the page \"\"\" # find pages containing",
"1 # get max-word frequency for each page page2max_word_frequency = {} # e.g.",
"self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set",
"page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens",
"file\"\"\" with open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf = False def",
"(importance = \" + str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation # ---------------------------------------------------------------",
"text file, and makes pages out of it\"\"\" with open(fname, 'r') as f:",
"an \"electronic book\" - one can add pages, save/load to file and search",
"not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF",
"0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for the text in",
"__get_words_for_page(self, page_index): \"\"\"Gets the set of words found in the given page\"\"\" if",
"__author__ = 'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import math",
"first_occurence = False if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence =",
"for word in s.split(' '): # skip empty words word = self.__filter_to_letters(word) word",
"range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top k important words",
"words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance = \" + str(wai[1]) + \")\")",
"page_index): \"\"\"Computes the TF.IDF for given word on given page\"\"\" if not self.can_do_tfidf:",
"the maximum width of the page \"\"\" print('-'*width) print(\"| Page \" + str(page_number",
"pages, then sorts the results by TF.IDF importance of the search phrase in",
"+ 1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance =",
"\") for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance =",
"find pages containing the text found_pages = [i for i in range(len(self._pages)) if",
"words = [word for word in self.__split_to_words(text)] # get the importance-score for each",
"class Book: \"\"\"Represents an \"electronic book\" - one can add pages, save/load to",
"the word for this page first_occurence = False if word not in page2word_frequency[i]:",
"with open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book",
"e.g. 'word' -> '15' page2word_frequency = {} # e.g. 47 -> ('word' ->",
"page2word_frequency[i] = {} for word in self.__split_to_words(page): # mark the occurence of the",
"False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and makes pages out",
"+= self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda x: x[1],",
"str(pas[0]) + \" (importance = \" + str(pas[1]) + \")\") def save_to_file(self, fname):",
"important words for given page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word,",
"as f: self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints",
"lines_per_page=20): \"\"\"Opens given text file, and makes pages out of it\"\"\" with open(fname,",
"i in found_pages: score = 0 for word in words: score += self.__tf_idf(word,",
"word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index):",
"def __tf(self, word, page_index): \"\"\"Computes the TF for given word\"\"\" if not self.can_do_tfidf:",
"pages, save/load to file and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation #",
"lines = f.readlines() buffer = [] for line in lines: buffer.append(line) if len(buffer)",
"None self._page2word_frequency = None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface # ---------------------------------------------------------------",
"a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname,",
"def search_for(self, text): \"\"\"Searches for the text in all the pages, then sorts",
"in self._pages[i]] # split the search string to words words = [word for",
"# get the importance-score for each found page pages_and_scores = [] for i",
"word.lower() if len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary",
"self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text):",
"self.__split_to_words(page): # mark the occurence of the word for this page first_occurence =",
"set of words found in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return",
"self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main",
"book, to the console One may specify the maximum width of the page",
"+ str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \"",
"self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return",
"Main # --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38)",
"out of it\"\"\" with open(fname, 'r') as f: lines = f.readlines() buffer =",
"2) for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for word",
"top k important words for given page\"\"\" words_and_importances = [] for word in",
"f: self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints the",
"then sorts the results by TF.IDF importance of the search phrase in the",
"with open(fname, 'r') as f: lines = f.readlines() buffer = [] for line",
"self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True)",
"page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x:",
"get max-word frequency for each page page2max_word_frequency = {} # e.g. 47 ->",
"in s.split(' '): # skip empty words word = self.__filter_to_letters(word) word = word.lower()",
"f.readlines() buffer = [] for line in lines: buffer.append(line) if len(buffer) == lines_per_page:",
"page of the book, to the console One may specify the maximum width",
"= self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page): # mark the occurence",
"filtered += c return filtered def __split_to_words(self, s): \"\"\"Splits the string s to",
"words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on page \" + str(page_number +",
"word: if not c.isalpha(): continue filtered += c return filtered def __split_to_words(self, s):",
"time we see this word for this page, we also increase the #",
"+ wai[0] + \" (importance = \" + str(wai[1]) + \")\") # ---------------------------------------------------------------",
"of pages having it if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] =",
"\"\"\"Represents an \"electronic book\" - one can add pages, save/load to file and",
"in self.__split_to_words(text)] # get the importance-score for each found page pages_and_scores = []",
"Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given word",
"increase the # of pages having it if first_occurence: if word not in",
"\"\"\" print('-'*width) print(\"| Page \" + str(page_number + 1)) print('-'*width) line = \"\"",
"return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for given word\"\"\" if not",
"if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf =",
"through them\"\"\" for word in s.split(' '): # skip empty words word =",
"= [word for word in self.__split_to_words(text)] # get the importance-score for each found",
"len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for the",
"# Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it",
"width=120): \"\"\"Prints the specified page of the book, to the console One may",
"self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and",
"them\"\"\" for word in s.split(' '): # skip empty words word = self.__filter_to_letters(word)",
"score)) # sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\"",
"self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and makes",
"len(line) == width: print(line) line = \"\" print(line) print('-'*width) print() def print_all(self, width=120):",
"= None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self,",
"by TF.IDF importance of the search phrase in the page \"\"\" # find",
"17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency =",
"--------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency",
"found page pages_and_scores = [] for i in found_pages: score = 0 for",
"TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word",
"for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = []",
"if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes",
"True page2word_frequency[i][word] += 1 # if this is the first time we see",
"pages having it if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0",
"+ str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the book to a specified",
"in word: if not c.isalpha(): continue filtered += c return filtered def __split_to_words(self,",
"--------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf = False",
"47 -> ('word' -> 2) for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i]",
"--------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- # Class",
"specified page of the book, to the console One may specify the maximum",
"import pickle import math # --------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class",
"print_important_words(self, page_number, k=10): \"\"\"Gets the top k important words for given page\"\"\" words_and_importances",
"== 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of",
"of the search phrase in the page \"\"\" # find pages containing the",
"add_page(self, page): \"\"\"Adds a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False",
"fname): \"\"\"Loads the book from specified file\"\"\" with open(fname, 'rb') as f: self._pages",
"[] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency = None",
"the TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if",
"makes pages out of it\"\"\" with open(fname, 'r') as f: lines = f.readlines()",
"def __split_to_words(self, s): \"\"\"Splits the string s to words (in a simplistic manner",
"== lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def",
"= None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a",
"if len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for",
"used in this class) and iterates through them\"\"\" for word in s.split(' '):",
"\"\"\"Gets the top k important words for given page\"\"\" words_and_importances = [] for",
"print(\"Search phrase \\\"\" + text + \"\\\" located in following pages (sorted by",
"self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on page",
"text in all the pages, then sorts the results by TF.IDF importance of",
"self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of words",
"self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top k important words for",
"+ n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of words found in the",
"get the importance-score for each found page pages_and_scores = [] for i in",
"def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\" # get the necessary",
"- Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" - one can",
"Imports # --------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- # Class - Book",
"self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to contain letters only\"\"\" filtered",
"open(fname, 'r') as f: lines = f.readlines() buffer = [] for line in",
"pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance = \" + str(pas[1]) +",
"# --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF",
"word, page_index): \"\"\"Computes the TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f",
"on the words word2number_of_pages_having_it = {} # e.g. 'word' -> '15' page2word_frequency =",
"print('-'*width) print(\"| Page \" + str(page_number + 1)) print('-'*width) line = \"\" for",
"1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance = \"",
"the importance-score for each found page pages_and_scores = [] for i in found_pages:",
"by importance): \") for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \"",
"0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word):",
"file, and makes pages out of it\"\"\" with open(fname, 'r') as f: lines",
"\"\"\"Opens given text file, and makes pages out of it\"\"\" with open(fname, 'r')",
"in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0:",
"the pages of the book, one by one, to the console\"\"\" for i",
"filtered to contain letters only\"\"\" filtered = \"\" for c in word: if",
"self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on page \" +",
"= 0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word))",
"__filter_to_letters(word): \"\"\"Returns the word filtered to contain letters only\"\"\" filtered = \"\" for",
"the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets",
"word, page_index): \"\"\"Computes the TF.IDF for given word on given page\"\"\" if not",
"self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency = None #",
"print(line) line = \"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the",
"if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the",
"Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page to the book\"\"\"",
"word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\" # get the",
"self.__split_to_words(text)] # get the importance-score for each found page pages_and_scores = [] for",
"width=120): \"\"\"Prints all the pages of the book, one by one, to the",
"+ \")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes",
"add pages, save/load to file and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation",
"False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency = None # --------------------------------------------------------------- #",
"width: print(line) line = \"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all",
"print(\"\\t\" + wai[0] + \" (importance = \" + str(wai[1]) + \")\") #",
"+ str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word,",
"mark the occurence of the word for this page first_occurence = False if",
"word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not in self._page2word_frequency[page_index]",
"f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\" with",
"max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True",
"# --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf =",
"Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" - one",
"of the book, to the console One may specify the maximum width of",
"in this class) and iterates through them\"\"\" for word in s.split(' '): #",
"page, we also increase the # of pages having it if first_occurence: if",
"if this is the first time we see this word for this page,",
"word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get max-word",
"page \"\"\" print('-'*width) print(\"| Page \" + str(page_number + 1)) print('-'*width) line =",
"__idf(self, word): \"\"\"Computes the IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word",
"+ \"\\\" located in following pages (sorted by importance): \") for pas in",
"x: x[1], reverse=True) print(\"Most important words on page \" + str(page_number + 1))",
"we see this word for this page, we also increase the # of",
"'): # skip empty words word = self.__filter_to_letters(word) word = word.lower() if len(word.strip())",
"TF.IDF importance of the search phrase in the page \"\"\" # find pages",
"the first time we see this word for this page, we also increase",
"and iterates through them\"\"\" for word in s.split(' '): # skip empty words",
"of words found in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys()",
"for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency",
"__compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\" # get the necessary stats",
"importance): \") for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) + \" (importance",
"# get the necessary stats on the words word2number_of_pages_having_it = {} # e.g.",
"self._page2word_frequency = None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def",
"new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self, fname, lines_per_page=20):",
"sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" + text",
"\" + str(pas[0]) + \" (importance = \" + str(pas[1]) + \")\") def",
"wai[0] + \" (importance = \" + str(wai[1]) + \")\") # --------------------------------------------------------------- #",
"phrase in the page \"\"\" # find pages containing the text found_pages =",
"the page \"\"\" # find pages containing the text found_pages = [i for",
"c in self._pages[page_number]: line += c if len(line) == width: print(line) line =",
"# --------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic",
"= True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b = Book()",
"# --------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- # Class - Book #",
"'word' -> '15' page2word_frequency = {} # e.g. 47 -> ('word' -> 2)",
"the search phrase in the page \"\"\" # find pages containing the text",
"the necessary stats on the words word2number_of_pages_having_it = {} # e.g. 'word' ->",
"score = 0 for word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score))",
"# find pages containing the text found_pages = [i for i in range(len(self._pages))",
"i in range(len(self._pages)) if text in self._pages[i]] # split the search string to",
"and makes pages out of it\"\"\" with open(fname, 'r') as f: lines =",
"pages of the book, one by one, to the console\"\"\" for i in",
"for wai in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance = \" +",
"given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the",
"\" (importance = \" + str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the",
"in self.__split_to_words(page): # mark the occurence of the word for this page first_occurence",
"0 word2number_of_pages_having_it[word] += 1 # get max-word frequency for each page page2max_word_frequency =",
"--------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- # Class - Book # ---------------------------------------------------------------",
"for computation of TF.IDF\"\"\" # get the necessary stats on the words word2number_of_pages_having_it",
"for this page first_occurence = False if word not in page2word_frequency[i]: page2word_frequency[i][word] =",
"page_index): \"\"\"Computes the TF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f =",
"buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf",
"[word for word in self.__split_to_words(text)] # get the importance-score for each found page",
"given page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda",
"width of the page \"\"\" print('-'*width) print(\"| Page \" + str(page_number + 1))",
"line = \"\" for c in self._pages[page_number]: line += c if len(line) ==",
"in self._pages[page_number]: line += c if len(line) == width: print(line) line = \"\"",
"this is the first time we see this word for this page, we",
"self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def",
"'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book from specified",
"open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book from",
"- one can add pages, save/load to file and search for phrases\"\"\" #",
"'15' page2word_frequency = {} # e.g. 47 -> ('word' -> 2) for i",
"TF.IDF for given word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word,",
"word in s.split(' '): # skip empty words word = self.__filter_to_letters(word) word =",
"necessary for computation of TF.IDF\"\"\" # get the necessary stats on the words",
"\"\"\"Searches for the text in all the pages, then sorts the results by",
"word = self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0: continue yield word",
"len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False",
"the results by TF.IDF importance of the search phrase in the page \"\"\"",
"print_page(self, page_number, width=120): \"\"\"Prints the specified page of the book, to the console",
"for word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort by",
"page_index): \"\"\"Gets the set of words found in the given page\"\"\" if not",
"the search string to words words = [word for word in self.__split_to_words(text)] #",
"= self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0: continue yield word def",
"empty words word = self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0: continue",
"fname): \"\"\"Saves the book to a specified file\"\"\" with open(fname, 'wb') as f:",
"return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF for given word\"\"\"",
"x[1], reverse=True) print(\"Most important words on page \" + str(page_number + 1)) for",
"# split the search string to words words = [word for word in",
"# --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\" - one can add pages,",
"= page2word_frequency self._page2max_word_frequency = page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main #",
"str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the book to a specified file\"\"\"",
"--------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents an \"electronic book\"",
"and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages",
"first time we see this word for this page, we also increase the",
"word2number_of_pages_having_it[word] += 1 # get max-word frequency for each page page2max_word_frequency = {}",
"contain letters only\"\"\" filtered = \"\" for c in word: if not c.isalpha():",
"specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads",
"\"\"\"Saves the book to a specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages,",
"def __filter_to_letters(word): \"\"\"Returns the word filtered to contain letters only\"\"\" filtered = \"\"",
"= [] for line in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear()",
"self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints the specified page of the",
"the occurence of the word for this page first_occurence = False if word",
"search_for(self, text): \"\"\"Searches for the text in all the pages, then sorts the",
"the book to a specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f)",
"i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page):",
"for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for word in",
"a specified file\"\"\" with open(fname, 'wb') as f: pickle.dump(self._pages, f) def load_from_file(self, fname):",
"text + \"\\\" located in following pages (sorted by importance): \") for pas",
"= word.lower() if len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats",
"def make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and makes pages out of",
"+= c if len(line) == width: print(line) line = \"\" print(line) print('-'*width) print()",
"= False def print_page(self, page_number, width=120): \"\"\"Prints the specified page of the book,",
"save/load to file and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # ---------------------------------------------------------------",
"for c in word: if not c.isalpha(): continue filtered += c return filtered",
"self.can_do_tfidf = True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b =",
"also increase the # of pages having it if first_occurence: if word not",
"to the console One may specify the maximum width of the page \"\"\"",
"s to words (in a simplistic manner used in this class) and iterates",
"page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF for given word\"\"\" if not",
"--------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given word on given",
"if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for",
"word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get max-word frequency for each page",
"in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word):",
"page2max_word_frequency = {} # e.g. 47 -> 17 for i in page2word_frequency: page2max_word_frequency[i]",
"if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not in self._word2number_of_pages_having_it else",
"= True page2word_frequency[i][word] += 1 # if this is the first time we",
"the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns",
"= [] for i in found_pages: score = 0 for word in words:",
"page2max_word_frequency self.can_do_tfidf = True # --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b",
"page first_occurence = False if word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence",
"= [] self.can_do_tfidf = False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency =",
"the top k important words for given page\"\"\" words_and_importances = [] for word",
"None self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page):",
"pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints the specified page of",
"page): \"\"\"Adds a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def",
"in the page \"\"\" # find pages containing the text found_pages = [i",
"1 # if this is the first time we see this word for",
"def add_page(self, page): \"\"\"Adds a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf =",
"+ \" (importance = \" + str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves",
"= \"\" for c in self._pages[page_number]: line += c if len(line) == width:",
"self._pages = pickle.load(f) self.can_do_tfidf = False def print_page(self, page_number, width=120): \"\"\"Prints the specified",
"of the page \"\"\" print('-'*width) print(\"| Page \" + str(page_number + 1)) print('-'*width)",
"c in word: if not c.isalpha(): continue filtered += c return filtered def",
"word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get max-word frequency for each",
"can add pages, save/load to file and search for phrases\"\"\" # --------------------------------------------------------------- #",
"page pages_and_scores = [] for i in found_pages: score = 0 for word",
"of the book, one by one, to the console\"\"\" for i in range(len(self._pages)):",
"for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top",
"(in a simplistic manner used in this class) and iterates through them\"\"\" for",
"def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\")",
"in self.__get_words_for_page(page_number): words_and_importances.append((word, self.__tf_idf(word, page_number))) words_and_importances.sort(key=lambda x: x[1], reverse=True) print(\"Most important words on",
"by one, to the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self,",
"of it\"\"\" with open(fname, 'r') as f: lines = f.readlines() buffer = []",
"the console One may specify the maximum width of the page \"\"\" print('-'*width)",
"the set of words found in the given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf()",
"(sorted by importance): \") for pas in pages_and_scores: print(\"\\tPage \" + str(pas[0]) +",
"importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" + text + \"\\\"",
"one by one, to the console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def",
"word not in page2word_frequency[i]: page2word_frequency[i][word] = 0 first_occurence = True page2word_frequency[i][word] += 1",
"= False self._word2number_of_pages_having_it = None self._page2word_frequency = None self._page2max_word_frequency = None # ---------------------------------------------------------------",
"word for this page first_occurence = False if word not in page2word_frequency[i]: page2word_frequency[i][word]",
"e.g. 47 -> 17 for i in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it =",
"for i in range(len(self._pages)) if text in self._pages[i]] # split the search string",
"\" + str(page_number + 1)) print('-'*width) line = \"\" for c in self._pages[page_number]:",
"skip empty words word = self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0:",
"importance-score for each found page pages_and_scores = [] for i in found_pages: score",
"console One may specify the maximum width of the page \"\"\" print('-'*width) print(\"|",
"# Imports # --------------------------------------------------------------- import pickle import math # --------------------------------------------------------------- # Class -",
"words words = [word for word in self.__split_to_words(text)] # get the importance-score for",
"for given word on given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word)",
"def load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\" with open(fname, 'rb') as",
"\"\"\"Adds a new page to the book\"\"\" self._pages.append(page) self.can_do_tfidf = False def make_pages_from_textfile(self,",
"return filtered def __split_to_words(self, s): \"\"\"Splits the string s to words (in a",
"-> 2) for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for",
"book from specified file\"\"\" with open(fname, 'rb') as f: self._pages = pickle.load(f) self.can_do_tfidf",
"not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF",
"f) def load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\" with open(fname, 'rb')",
"this page, we also increase the # of pages having it if first_occurence:",
"specify the maximum width of the page \"\"\" print('-'*width) print(\"| Page \" +",
"+ str(pas[0]) + \" (importance = \" + str(pas[1]) + \")\") def save_to_file(self,",
"given page\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index):",
"self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to contain",
"in following pages (sorted by importance): \") for pas in pages_and_scores: print(\"\\tPage \"",
"word = word.lower() if len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes",
"s): \"\"\"Splits the string s to words (in a simplistic manner used in",
"range(len(self._pages)) if text in self._pages[i]] # split the search string to words words",
"as f: pickle.dump(self._pages, f) def load_from_file(self, fname): \"\"\"Loads the book from specified file\"\"\"",
"if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self,",
"iterates through them\"\"\" for word in s.split(' '): # skip empty words word",
"phrase \\\"\" + text + \"\\\" located in following pages (sorted by importance):",
"__tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given word on given page\"\"\" if",
"pickle import math # --------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class Book:",
"page_number, width=120): \"\"\"Prints the specified page of the book, to the console One",
"self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return",
"= {} # e.g. 47 -> 17 for i in page2word_frequency: page2max_word_frequency[i] =",
"f = 0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def",
"= 0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self,",
"-> ('word' -> 2) for i in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] =",
"by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" + text +",
"the specified page of the book, to the console One may specify the",
"\"\"\"Gets the set of words found in the given page\"\"\" if not self.can_do_tfidf:",
"self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for given",
"width) def print_important_words(self, page_number, k=10): \"\"\"Gets the top k important words for given",
"c if len(line) == width: print(line) line = \"\" print(line) print('-'*width) print() def",
"print('-'*width) line = \"\" for c in self._pages[page_number]: line += c if len(line)",
"given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not in",
"self.__filter_to_letters(word) word = word.lower() if len(word.strip()) == 0: continue yield word def __compute_stats_for_tfidf(self):",
"<gh_stars>0 __author__ = 'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import pickle import",
"lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer) != 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self,",
"if not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered",
"0 first_occurence = True page2word_frequency[i][word] += 1 # if this is the first",
"having it if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word]",
"self._page2max_word_frequency = None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds",
"may specify the maximum width of the page \"\"\" print('-'*width) print(\"| Page \"",
"of the word for this page first_occurence = False if word not in",
"x[1], reverse=True) print(\"Search phrase \\\"\" + text + \"\\\" located in following pages",
"str(page_number + 1)) print('-'*width) line = \"\" for c in self._pages[page_number]: line +=",
"for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not",
"+= 1 # if this is the first time we see this word",
"b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10) if",
"print(\"\\tPage \" + str(pas[0]) + \" (importance = \" + str(pas[1]) + \")\")",
"def __idf(self, word): \"\"\"Computes the IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf()",
"word in self.__split_to_words(page): # mark the occurence of the word for this page",
"max-word frequency for each page page2max_word_frequency = {} # e.g. 47 -> 17",
"# --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for given word on",
"word in self.__split_to_words(text)] # get the importance-score for each found page pages_and_scores =",
"math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets the set of words found in",
"\"electronic book\" - one can add pages, save/load to file and search for",
"None # --------------------------------------------------------------- # Interface # --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new",
"in words_and_importances[:k]: print(\"\\t\" + wai[0] + \" (importance = \" + str(wai[1]) +",
"self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to contain letters",
"pages_and_scores.append((i, score)) # sort by importance score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase",
"pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" + text + \"\\\" located in",
"= \"\" print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the pages of",
"self.can_do_tfidf: self.__compute_stats_for_tfidf() return self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF for",
"\"\"\"Loads the book from specified file\"\"\" with open(fname, 'rb') as f: self._pages =",
"page \" + str(page_number + 1)) for wai in words_and_importances[:k]: print(\"\\t\" + wai[0]",
"file and search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self):",
"page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency = page2max_word_frequency",
"# e.g. 47 -> ('word' -> 2) for i in range(len(self._pages)): page =",
"word for this page, we also increase the # of pages having it",
"0: continue yield word def __compute_stats_for_tfidf(self): \"\"\"Computes stats necessary for computation of TF.IDF\"\"\"",
"in page2word_frequency: page2max_word_frequency[i] = max(page2word_frequency[i].values()) self._word2number_of_pages_having_it = word2number_of_pages_having_it self._page2word_frequency = page2word_frequency self._page2max_word_frequency =",
"# if this is the first time we see this word for this",
"--------------------------------------------------------------- # Implementation # --------------------------------------------------------------- def __tf_idf(self, word, page_index): \"\"\"Computes the TF.IDF for",
"!= 0: self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for the text",
"make_pages_from_textfile(self, fname, lines_per_page=20): \"\"\"Opens given text file, and makes pages out of it\"\"\"",
"= [i for i in range(len(self._pages)) if text in self._pages[i]] # split the",
"\"\"\"Prints all the pages of the book, one by one, to the console\"\"\"",
"console\"\"\" for i in range(len(self._pages)): self.print_page(i, width) def print_important_words(self, page_number, k=10): \"\"\"Gets the",
"def print_important_words(self, page_number, k=10): \"\"\"Gets the top k important words for given page\"\"\"",
"in range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page): #",
"results by TF.IDF importance of the search phrase in the page \"\"\" #",
"(importance = \" + str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the book",
"x: x[1], reverse=True) print(\"Search phrase \\\"\" + text + \"\\\" located in following",
"+ \" (importance = \" + str(wai[1]) + \")\") # --------------------------------------------------------------- # Implementation",
"0 for word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i, score)) # sort",
"n_word = 0 if word not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 +",
"is the first time we see this word for this page, we also",
"print_all(self, width=120): \"\"\"Prints all the pages of the book, one by one, to",
"# --------------------------------------------------------------- # Main # --------------------------------------------------------------- def main(): b = Book() b.make_pages_from_textfile('animal_farm.txt') b.print_page(0)",
"\" + str(pas[1]) + \")\") def save_to_file(self, fname): \"\"\"Saves the book to a",
"maximum width of the page \"\"\" print('-'*width) print(\"| Page \" + str(page_number +",
"range(len(self._pages)): page = self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page): # mark",
"located in following pages (sorted by importance): \") for pas in pages_and_scores: print(\"\\tPage",
"self._pages[i]] # split the search string to words words = [word for word",
"s.split(' '): # skip empty words word = self.__filter_to_letters(word) word = word.lower() if",
"not self.can_do_tfidf: self.__compute_stats_for_tfidf() f = 0 if word not in self._page2word_frequency[page_index] else self._page2word_frequency[page_index][word]",
"given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if word not in",
"words word2number_of_pages_having_it = {} # e.g. 'word' -> '15' page2word_frequency = {} #",
"@staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to contain letters only\"\"\" filtered =",
"for c in self._pages[page_number]: line += c if len(line) == width: print(line) line",
"k=10): \"\"\"Gets the top k important words for given page\"\"\" words_and_importances = []",
"not in self._word2number_of_pages_having_it else self._word2number_of_pages_having_it[word] return math.log(len(self._pages)/(1 + n_word)) def __get_words_for_page(self, page_index): \"\"\"Gets",
"simplistic manner used in this class) and iterates through them\"\"\" for word in",
"it if first_occurence: if word not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] +=",
"search for phrases\"\"\" # --------------------------------------------------------------- # Initialisation # --------------------------------------------------------------- def __init__(self): self._pages =",
"the text in all the pages, then sorts the results by TF.IDF importance",
"k important words for given page\"\"\" words_and_importances = [] for word in self.__get_words_for_page(page_number):",
"not self.can_do_tfidf: self.__compute_stats_for_tfidf() return self._page2word_frequency[page_index].keys() @staticmethod def __filter_to_letters(word): \"\"\"Returns the word filtered to",
"\"\"\"Prints the specified page of the book, to the console One may specify",
"Initialisation # --------------------------------------------------------------- def __init__(self): self._pages = [] self.can_do_tfidf = False self._word2number_of_pages_having_it =",
"'r') as f: lines = f.readlines() buffer = [] for line in lines:",
"import math # --------------------------------------------------------------- # Class - Book # --------------------------------------------------------------- class Book: \"\"\"Represents",
"b.print_page(0) b.print_important_words(0) b.search_for(\"pig\") b.print_important_words(38) b.search_for(\"point of view\") b.print_page(10) if __name__ == '__main__': main()",
"score pages_and_scores.sort(key=lambda x: x[1], reverse=True) print(\"Search phrase \\\"\" + text + \"\\\" located",
"for line in lines: buffer.append(line) if len(buffer) == lines_per_page: self.add_page(\"\\n\".join(buffer)) buffer.clear() if len(buffer)",
"\")\") def save_to_file(self, fname): \"\"\"Saves the book to a specified file\"\"\" with open(fname,",
"# --------------------------------------------------------------- def add_page(self, page): \"\"\"Adds a new page to the book\"\"\" self._pages.append(page)",
"the # of pages having it if first_occurence: if word not in word2number_of_pages_having_it:",
"split the search string to words words = [word for word in self.__split_to_words(text)]",
"to words (in a simplistic manner used in this class) and iterates through",
"found_pages: score = 0 for word in words: score += self.__tf_idf(word, i) pages_and_scores.append((i,",
"the book from specified file\"\"\" with open(fname, 'rb') as f: self._pages = pickle.load(f)",
"a simplistic manner used in this class) and iterates through them\"\"\" for word",
"One may specify the maximum width of the page \"\"\" print('-'*width) print(\"| Page",
"# mark the occurence of the word for this page first_occurence = False",
"this word for this page, we also increase the # of pages having",
"self._pages[i] page2word_frequency[i] = {} for word in self.__split_to_words(page): # mark the occurence of",
"important words on page \" + str(page_number + 1)) for wai in words_and_importances[:k]:",
"self.add_page(\"\\n\".join(buffer)) self.can_do_tfidf = False def search_for(self, text): \"\"\"Searches for the text in all",
"print(line) print('-'*width) print() def print_all(self, width=120): \"\"\"Prints all the pages of the book,",
"the IDF for given word\"\"\" if not self.can_do_tfidf: self.__compute_stats_for_tfidf() n_word = 0 if",
"continue filtered += c return filtered def __split_to_words(self, s): \"\"\"Splits the string s",
"Page \" + str(page_number + 1)) print('-'*width) line = \"\" for c in",
"only\"\"\" filtered = \"\" for c in word: if not c.isalpha(): continue filtered",
"not in word2number_of_pages_having_it: word2number_of_pages_having_it[word] = 0 word2number_of_pages_having_it[word] += 1 # get max-word frequency",
"= 0 first_occurence = True page2word_frequency[i][word] += 1 # if this is the",
"self._page2word_frequency[page_index][word] return f/self._page2max_word_frequency[page_index] def __idf(self, word): \"\"\"Computes the IDF for given word\"\"\" if",
"self.__tf(word, page_index)*self.__idf(word) def __tf(self, word, page_index): \"\"\"Computes the TF for given word\"\"\" if",
"for this page, we also increase the # of pages having it if"
] |
[
"AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value",
"'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) ==",
"result = AccessControlEntry() if not content: return result if 'Trustee' in content: result.Trustee",
"@property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee",
"self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value @property def AccessRights(self) ->",
"self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self,",
"self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry() if not",
"def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights =",
"= None): self.Trustee = trustee self.AccessType = access_type self.AccessRights = access_rights @property def",
"self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry() if not content: return",
"value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum):",
"definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum",
"= value @property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value:",
"content: return result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in",
"self.Trustee = trustee self.AccessType = access_type self.AccessRights = access_rights @property def Trustee(self) ->",
"= access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value:",
"== str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in content:",
"@AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def",
"= trustee self.AccessType = access_type self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee':",
"import IntEnum import json from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from",
"and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights'",
"-> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value @property",
"toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod",
"'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else: result.AccessRights = CommonAccessRightsEnum.none return result",
"@property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights",
"int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) == str: result.AccessType",
"json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content:",
"from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self,",
"def Trustee(self, value: 'Trustee'): self.__trustee = value @property def AccessType(self) -> 'AccessType': return",
"self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry()",
"self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType':",
"= AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum(",
"@property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type",
"import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS",
"self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary())",
"-> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def",
"access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType =",
"fromJson(content: dict[str, str]): result = AccessControlEntry() if not content: return result if 'Trustee'",
"'AccessType' in content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType =",
"AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else:",
"value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee':",
"'Trustee'): self.__trustee = value @property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def",
"access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'):",
"import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\"",
"def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee =",
"in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) == int:",
"None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType",
"in content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content",
"AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type:",
"== int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) == str:",
"= AccessControlEntry() if not content: return result if 'Trustee' in content: result.Trustee =",
"@staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry() if not content: return result",
"content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) == int: result.AccessType",
"result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) == int: result.AccessType =",
"content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if",
"result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and",
"dict[str, str]): result = AccessControlEntry() if not content: return result if 'Trustee' in",
"and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType'])",
"IntEnum import json from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee",
"return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return",
"\"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType'",
"access_type self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def",
"import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee: 'Trustee'",
"self.AccessType = access_type self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee",
"def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str,",
"Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee: 'Trustee' =",
"toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]):",
"result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else: result.AccessRights",
"access control entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' =",
"CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(),",
"= value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value:",
"'Trustee' = None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee =",
"= None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee",
"= AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else: result.AccessRights =",
"entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' = None, access_rights:",
"def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self):",
"'AccessType' in content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in",
"access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType = access_type self.AccessRights = access_rights",
"def fromJson(content: dict[str, str]): result = AccessControlEntry() if not content: return result if",
"AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access",
"type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in",
"return result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content",
"class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None,",
"def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum =",
"Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value",
"value @property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'):",
"enum import IntEnum import json from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum",
"'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry() if not content:",
"if 'AccessType' in content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType'",
"__init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None):",
"def AccessType(self, value: 'AccessType'): self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum: return",
"value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights':",
"<gh_stars>1-10 from enum import IntEnum import json from .AccessType import AccessType from .CommonAccessRightsEnum",
"= None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType = access_type self.AccessRights",
"else: result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else:",
"'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType = access_type",
"self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value @property def AccessType(self) ->",
"return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value @property def AccessRights(self)",
"return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result",
"value: 'AccessType'): self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter",
"result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) == str: result.AccessType =",
"if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType'])",
"= value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value,",
"@AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum:",
"from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control",
"AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value",
"self.__trustee = value @property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self,",
"value: 'Trustee'): self.__trustee = value @property def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter",
".Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def __init__(self, trustee:",
"CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType = access_type self.AccessRights = access_rights @property",
"elif 'AccessType' in content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType",
"AccessType(self, value: 'AccessType'): self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights",
"@Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value @property def AccessType(self) -> 'AccessType':",
"'Trustee': return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value @property def",
"CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry definition\"\"\" def",
"CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self):",
"str]): result = AccessControlEntry() if not content: return result if 'Trustee' in content:",
"= Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType'])",
"trustee: 'Trustee' = None, access_type: 'AccessType' = None, access_rights: CommonAccessRightsEnum = None): self.Trustee",
"from enum import IntEnum import json from .AccessType import AccessType from .CommonAccessRightsEnum import",
"self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter def Trustee(self,",
"json from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee",
"if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else: result.AccessRights = CommonAccessRightsEnum.none return",
".CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object): \"\"\"OCS access control entry",
"'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value @property def",
"-> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type = value @property",
"AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights']) else: result.AccessRights = CommonAccessRightsEnum.none",
"AccessRights(self, value: CommonAccessRightsEnum): self.__access_rights = value def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return",
"not content: return result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if 'AccessType'",
"result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights =",
"'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result = AccessControlEntry() if",
"import json from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import",
"return self.__trustee @Trustee.setter def Trustee(self, value: 'Trustee'): self.__trustee = value @property def AccessType(self)",
"AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights = CommonAccessRightsEnum( content['AccessRights'])",
"'AccessType'): self.__access_type = value @property def AccessRights(self) -> CommonAccessRightsEnum: return self.__access_rights @AccessRights.setter def",
"def AccessType(self) -> 'AccessType': return self.__access_type @AccessType.setter def AccessType(self, value: 'AccessType'): self.__access_type =",
"Trustee.fromJson(content['Trustee']) if 'AccessType' in content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif",
"= access_type self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee': return self.__trustee @Trustee.setter",
"from .AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class",
"type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) ==",
".AccessType import AccessType from .CommonAccessRightsEnum import CommonAccessRightsEnum from .Trustee import Trustee class AccessControlEntry(object):",
"Trustee(self, value: 'Trustee'): self.__trustee = value @property def AccessType(self) -> 'AccessType': return self.__access_type",
"in content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed",
"None): self.Trustee = trustee self.AccessType = access_type self.AccessRights = access_rights @property def Trustee(self)",
"None, access_rights: CommonAccessRightsEnum = None): self.Trustee = trustee self.AccessType = access_type self.AccessRights =",
"= AccessType(content['AccessType']) elif 'AccessType' in content and type(content['AccessType']) == str: result.AccessType = AccessType[content['AccessType']]",
"trustee self.AccessType = access_type self.AccessRights = access_rights @property def Trustee(self) -> 'Trustee': return",
"if not content: return result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee']) if",
"def toJson(self): return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value}",
"control entry definition\"\"\" def __init__(self, trustee: 'Trustee' = None, access_type: 'AccessType' = None,",
"return json.dumps(self.toDictionary()) def toDictionary(self): return {'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def",
"content and type(content['AccessType']) == int: result.AccessType = AccessType(content['AccessType']) elif 'AccessType' in content and",
"str: result.AccessType = AccessType[content['AccessType']] else: result.AccessType = AccessType.Allowed if 'AccessRights' in content: result.AccessRights",
"{'Trustee': self.Trustee.toDictionary(), 'AccessType': self.AccessType.value, 'AccessRights': self.AccessRights.value} @staticmethod def fromJson(content: dict[str, str]): result =",
"AccessControlEntry() if not content: return result if 'Trustee' in content: result.Trustee = Trustee.fromJson(content['Trustee'])"
] |
[
"tf.close() for i in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] =",
"_ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t = TestOdometry()",
"None if not record and results is None: inputs, results = self._load_recording(pickle_file) else:",
"DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False,",
"sun shines on the lens **common_kwargs ) if __name__ == '__main__': import sys",
"def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944",
"None else (msg + ': norm(%s) %f > %f' % (ord, norm, delta)))",
"# dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst)",
"and sys.argv[1] == 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from",
"'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs =",
"3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera(",
"# y fov in degrees f_stop=5, # TODO: put better value here point_spread_fn=0.50,",
"inputs = [] for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i",
"* sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov,",
"tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9))",
"poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate')",
"delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is",
"as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs():",
"math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None else (msg +",
"%f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0",
"# ratio of brightness in center pixel scattering_coef=2e-10, # affects strength of haze/veil",
"not record and results is None: inputs, results = self._load_recording(pickle_file) else: results =",
"quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in",
"import cv2 from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo",
"1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best =",
"deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses')",
"result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1 msg",
"result0 pose1, bias_sds1, scale_sd1 = result1 msg = '%s deviate(s) too much from",
"= os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not None and results is",
"np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq =",
"= cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light,",
"= [] for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i *",
"tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist':",
"i in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE)",
"the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf,",
"real one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results): tf",
"{ 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose,",
"pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with open(tf.name, 'wb')",
"0: for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey()",
"expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error",
"msg=None): if arr0 is None and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1),",
"# width in pixels 1944, # height in pixels 7.7, # x fov",
"self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i",
"i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image =",
"estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file =",
"pose1.quat, delta=delta_q, msg=None if msg is None else (msg + ': quat %s",
"norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0",
"6 & 5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309, # y fov",
"for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image",
"if pose0 is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2,",
"bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self,",
"self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def",
"much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1,",
"quaternion import cv2 from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose from",
"cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q",
"else (msg + ': norm(%s) %f > %f' % (ord, norm, delta))) def",
"from datetime import datetime import numpy as np import quaternion import cv2 from",
"diff, delta=delta, msg=None if msg is None else (msg + ': angle[deg] %f",
"import tempfile import os import math from datetime import datetime import numpy as",
"in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t = TestOdometry() t.setUp(verbose=True)",
"import RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re =",
"as np import quaternion import cv2 from visnav.algo.model import Camera from visnav.algo.odometry import",
"time, prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i >",
"= re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q =",
"pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and pose1 is None:",
"from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self,",
"0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff':",
"cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t = TestOdometry() t.setUp(verbose=True) t.test_rotating_object(inputs=inputs) else: unittest.main()",
"SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import *",
"elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to",
"delta_q=10, msg='estimated pose deviates too much from the real one') if record: self._save_recording(pickle_file,",
"os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with",
"est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0",
"inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t = TestOdometry() t.setUp(verbose=True) t.test_rotating_object(inputs=inputs)",
"self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from the real one')",
"msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record",
"record = inputs is not None and results is None if not record",
"0.01) res = self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i],",
"= { 'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200,",
"= dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v",
"= re.load_object(obj) light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0,",
"scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data',",
"res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from the real one') if",
"= result0 pose1, bias_sds1, scale_sd1 = result1 msg = '%s deviate(s) too much",
"0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0",
"delta=delta_q, msg=None if msg is None else (msg + ': quat %s vs",
"norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None else",
"norm(%s) %f > %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1:",
"cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None,",
"msg is None else (msg + ': norm(%s) %f > %f' % (ord,",
"for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else:",
"from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools",
"assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None and arr1 is",
"+ ': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0,",
"visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools class",
"else: results = [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp()",
"tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with open(tf.name, 'wb') as",
"datetime import datetime import numpy as np import quaternion import cv2 from visnav.algo.model",
"in center pixel scattering_coef=2e-10, # affects strength of haze/veil when sun shines on",
"in degrees f_stop=5, # TODO: put better value here point_spread_fn=0.50, # ratio of",
"lens **common_kwargs ) if __name__ == '__main__': import sys if len(sys.argv) > 1",
"from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params",
"and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is",
"= quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q)",
"i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res =",
"= get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo",
"= tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with open(tf.name, 'wb') as fh:",
"%f > %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose,",
"pixel scattering_coef=2e-10, # affects strength of haze/veil when sun shines on the lens",
"not None and results is None if not record and results is None:",
"cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q *",
"if quat0 is None and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1))",
"affects strength of haze/veil when sun shines on the lens **common_kwargs ) if",
"msg=None if msg is None else (msg + ': angle[deg] %f > %f'",
"obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 =",
"brightness in center pixel scattering_coef=2e-10, # affects strength of haze/veil when sun shines",
"gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj()",
"* 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9,",
"cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for",
"msg=None): if quat0 is None and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0,",
"import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import",
"cam_ast_cv_q]) if 0: for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5,",
"sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0,",
"visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0)",
"2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5]) light",
"'rb') as fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for",
"15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time",
"%f > %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None):",
"'test_rotating_object.pickle') record = inputs is not None and results is None if not",
"is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg",
"0, 1, 0)) inputs = [] for i in range(60): cam_ast_v = cam_ast_v0",
"np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None else (msg +",
"+ i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res",
"1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10,",
"results is None if not record and results is None: inputs, results =",
"def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is None and quat1 is",
"}) common_kwargs = common_kwargs_best return Camera( 2048, # width in pixels 1944, #",
"'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False,",
"10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False,",
"light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q *",
"is None else (msg + ': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self,",
"results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not None and",
"= [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i,",
"cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = {",
"%s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1,",
"cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name)",
"datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01)",
"'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should",
"= np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0,",
"+ ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg",
"sys if len(sys.argv) > 1 and sys.argv[1] == 'record': from visnav.algo.model import SystemModel",
"quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if",
"from the real one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs,",
"as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname, 'rb') as fh:",
"inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0],",
"diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None else",
"get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from",
"': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0",
"= dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5,",
"None and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta,",
"self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1,",
"> 1 and sys.argv[1] == 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import",
"delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None,",
"quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None else (msg + ':",
"= SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image,",
"msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file",
"of haze/veil when sun shines on the lens **common_kwargs ) if __name__ ==",
"return inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048",
"'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9,",
"dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({",
"'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine",
"np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7])",
"with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname,",
"* 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e))",
"0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = []",
"arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None and arr1 is None: return",
"[] for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0",
"%s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0",
"20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e':",
"fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in",
"res = self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res)",
"sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05,",
"self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None else (msg + ': norm(%s)",
"results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION,",
"bias_sds1, scale_sd1 = result1 msg = '%s deviate(s) too much from the expected",
"visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params =",
"'%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time +",
"= self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if",
"and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated",
"'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1,",
"msg is None else (msg + ': angle[deg] %f > %f' % (diff,",
"delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None and",
"too much from the real one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self,",
"'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs,",
"quat1, delta=1e-4, msg=None): if quat0 is None and quat1 is None: return diff",
"is None else (msg + ': angle[deg] %f > %f' % (diff, delta)))",
"shines on the lens **common_kwargs ) if __name__ == '__main__': import sys if",
"open(fname, 'rb') as fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close()",
"is None if not record and results is None: inputs, results = self._load_recording(pickle_file)",
"': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is",
"pose0 is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None",
"common_kwargs_best return Camera( 2048, # width in pixels 1944, # height in pixels",
"cv2 from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import",
"'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max",
"pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1 msg = '%s",
"= '%s deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1,",
"pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is None and quat1",
"angle[deg] %f > %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf,",
"= datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) *",
"-0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 =",
"scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1 msg = '%s deviate(s) too",
"antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light =",
"* SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _ in inputs:",
"i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0],",
"deviates too much from the real one') if record: self._save_recording(pickle_file, inputs, results) def",
"re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q",
"is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is None else",
"self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__),",
"fov in degrees f_stop=5, # TODO: put better value here point_spread_fn=0.50, # ratio",
"range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v,",
"import datetime import numpy as np import quaternion import cv2 from visnav.algo.model import",
"= pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with open(tf.name,",
"DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj",
"= tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for i in range(60): cam_ast_v",
"image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q",
"quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 =",
"'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera( 2048, # width in pixels",
"self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates",
"& 4.89, 7.7 & 7.309) 7.309, # y fov in degrees f_stop=5, #",
"datetime import numpy as np import quaternion import cv2 from visnav.algo.model import Camera",
"self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is None else (msg + ':",
"**common_kwargs ) if __name__ == '__main__': import sys if len(sys.argv) > 1 and",
"fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname, 'rb') as fh: inputs,",
"= common_kwargs_best return Camera( 2048, # width in pixels 1944, # height in",
"RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj)",
"os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not None and results is None",
"arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if",
"= tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q])",
"re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1,",
"= { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4,",
"target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj =",
"pose1.loc, delta=delta_v, ord=2, msg=None if msg is None else (msg + ': loc",
"pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from the",
"delta=1e-7, ord=np.inf, msg=None): if arr0 is None and arr1 is None: return norm",
"_save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)):",
"estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs",
"be 6 & 5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309, # y",
"'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False,",
"self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close()",
"import quaternion import cv2 from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry, Pose",
"msg=None if msg is None else (msg + ': norm(%s) %f > %f'",
"dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v =",
"numpy as np import quaternion import cv2 from visnav.algo.model import Camera from visnav.algo.odometry",
"pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None):",
"inputs is not None and results is None if not record and results",
"return Camera( 2048, # width in pixels 1944, # height in pixels 7.7,",
"cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8,",
"use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if",
"from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1,",
"'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500,",
"msg is None else (msg + ': quat %s vs %s'%(pose0.quat, pose1.quat))) def",
"= VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self,",
"import math from datetime import datetime import numpy as np import quaternion import",
"visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False):",
"vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1,",
"_load_recording(self, fname): with open(fname, 'rb') as fh: inputs, results = pickle.load(fh) tf =",
"12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params)",
"[] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img,",
"re.load_object(obj) light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0,",
"25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera( 2048, #",
"0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best",
"'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def",
"in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) *",
"= 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32,",
"= DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2)",
"(msg + ': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0,",
"sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light",
"if msg is None else (msg + ': norm(%s) %f > %f' %",
"width in pixels 1944, # height in pixels 7.7, # x fov in",
"msg = '%s deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02,",
"% (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is",
"(ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if",
"open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results",
"as fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i",
"== 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import",
"cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0:",
"for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior",
"common_kwargs = common_kwargs_best return Camera( 2048, # width in pixels 1944, # height",
"tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is None and",
"0)) inputs = [] for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q =",
"results = self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01",
"self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0,",
"self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d",
"'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25,",
"results), fh) def _load_recording(self, fname): with open(fname, 'rb') as fh: inputs, results =",
"pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1,",
"6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range",
"arr0 is None and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0,",
"f_stop=5, # TODO: put better value here point_spread_fn=0.50, # ratio of brightness in",
"%H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60)",
"* cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _",
"delta=1e-4, msg=None): if quat0 is None and quat1 is None: return diff =",
"too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0,",
"def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 =",
"(msg + ': angle[deg] %f > %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0,",
"ord=np.inf, msg=None): if arr0 is None and arr1 is None: return norm =",
"delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle')",
"and results is None: inputs, results = self._load_recording(pickle_file) else: results = [] cam_q",
"cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,))",
"import numpy as np import quaternion import cv2 from visnav.algo.model import Camera from",
"# height in pixels 7.7, # x fov in degrees (could be 6",
"7.7 & 7.309) 7.309, # y fov in degrees f_stop=5, # TODO: put",
"fname): with open(fname, 'rb') as fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png',",
"for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh:",
"msg is None else (msg + ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat,",
"delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale",
"0.05, 2) obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5])",
"9)) with open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb')",
"= RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx =",
"cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v)",
"np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior, cam_q) if",
"quat0 is None and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0,",
"None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is None else (msg",
"import os import math from datetime import datetime import numpy as np import",
"pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1",
"if not record and results is None: inputs, results = self._load_recording(pickle_file) else: results",
"-sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs",
"is None else (msg + ': norm(%s) %f > %f' % (ord, norm,",
"# x fov in degrees (could be 6 & 5.695, 5.15 & 4.89,",
"if msg is None else (msg + ': loc %s vs %s'%(pose0.loc, pose1.loc)))",
"be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90,",
"in pixels 7.7, # x fov in degrees (could be 6 & 5.695,",
"'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def",
"cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1),",
"ord=2, msg=None if msg is None else (msg + ': loc %s vs",
"pixels 7.7, # x fov in degrees (could be 6 & 5.695, 5.15",
"time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,))",
"quat0, quat1, delta=1e-4, msg=None): if quat0 is None and quat1 is None: return",
"== '__main__': import sys if len(sys.argv) > 1 and sys.argv[1] == 'record': from",
"from visnav.render.render import RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True)",
"range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0] = fh.read()",
"value here point_spread_fn=0.50, # ratio of brightness in center pixel scattering_coef=2e-10, # affects",
"delta=delta, msg=None if msg is None else (msg + ': angle[deg] %f >",
"re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model obj_idx",
"+ ': norm(%s) %f > %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0:",
"value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates')",
"self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None else (msg + ': angle[deg]",
"= tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with",
"i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0]",
"import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov,",
"'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic",
"if __name__ == '__main__': import sys if len(sys.argv) > 1 and sys.argv[1] ==",
"import unittest import pickle import tempfile import os import math from datetime import",
"cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _ in",
"else (msg + ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None",
"tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as",
"pose deviates too much from the real one') if record: self._save_recording(pickle_file, inputs, results)",
"cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst =",
"ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error estimate') def test_rotating_object(self, inputs=None, results=None):",
"* 0.01) res = self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif 0:",
"range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return",
"800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef':",
"cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q,",
"15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise))",
"delta=delta, msg=None if msg is None else (msg + ': norm(%s) %f >",
"open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname, 'rb')",
"inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 *",
"None and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta,",
"light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance",
"inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def",
"vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None else (msg",
"if msg is None else (msg + ': angle[deg] %f > %f' %",
"norm, delta=delta, msg=None if msg is None else (msg + ': norm(%s) %f",
"pose1, bias_sds1, scale_sd1 = result1 msg = '%s deviate(s) too much from the",
"& 7.309) 7.309, # y fov in degrees f_stop=5, # TODO: put better",
"VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0,",
"'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera( 2048,",
"if arr0 is None and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord)",
"light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one",
"> %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if",
"is None and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff,",
"90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd':",
"dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55,",
"pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname, 'rb') as fh: inputs, results",
"cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and",
"degrees f_stop=5, # TODO: put better value here point_spread_fn=0.50, # ratio of brightness",
"assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and",
"TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers':",
"import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params = {",
"enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1,",
"visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings",
"from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import * sm",
"2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu':",
"def setUp(self, verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12,",
"fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname):",
"import pickle import tempfile import os import math from datetime import datetime import",
"range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff':",
"Camera( 2048, # width in pixels 1944, # height in pixels 7.7, #",
"x fov in degrees (could be 6 & 5.695, 5.15 & 4.89, 7.7",
"import sys if len(sys.argv) > 1 and sys.argv[1] == 'record': from visnav.algo.model import",
"np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior, cam_q) if record: results.append(res) elif",
"'data', 'test_rotating_object.pickle') record = inputs is not None and results is None if",
"inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def get_cam():",
"(img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior = Pose(cam_obj_v,",
"inputs, results) def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for",
"estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from the real",
"should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y':",
"5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309, # y fov in degrees",
"def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None and arr1",
"/= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq",
"delta=delta_v, ord=2, msg=None if msg is None else (msg + ': loc %s",
"in degrees (could be 6 & 5.695, 5.15 & 4.89, 7.7 & 7.309)",
"self.cam = get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, }",
"* 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs =",
"inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not None",
"if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0:",
"350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd",
"math from datetime import datetime import numpy as np import quaternion import cv2",
"= fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self,",
"tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name,",
"record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False)",
"None else (msg + ': angle[deg] %f > %f' % (diff, delta))) def",
"Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and pose1 is",
"return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None",
"pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is None",
"the real one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results):",
"1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min':",
"pixels 1944, # height in pixels 7.7, # x fov in degrees (could",
"None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is",
"is None and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm,",
"= self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00',",
"sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0",
"get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944 *",
"(msg + ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if",
"def _load_recording(self, fname): with open(fname, 'rb') as fh: inputs, results = pickle.load(fh) tf",
"= sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5]) light /= np.linalg.norm(light)",
"def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is None",
"7.7, # x fov in degrees (could be 6 & 5.695, 5.15 &",
"record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0: self.assertIsNotNone(res[0],",
"verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4,",
"None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is",
"and arr1 is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None",
"'__main__': import sys if len(sys.argv) > 1 and sys.argv[1] == 'record': from visnav.algo.model",
"hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height, antialias_samples=0) re.set_frustum(sm.cam.x_fov, sm.cam.y_fov, 0.05, 2) obj = sm.asteroid.real_shape_model",
"def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff':",
"580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be",
"None else (msg + ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q,",
"results) def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i",
"4.89, 7.7 & 7.309) 7.309, # y fov in degrees f_stop=5, # TODO:",
"dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15,",
"msg=None if msg is None else (msg + ': loc %s vs %s'%(pose0.loc,",
"ratio of brightness in center pixel scattering_coef=2e-10, # affects strength of haze/veil when",
"cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t = TestOdometry() t.setUp(verbose=True) t.test_rotating_object(inputs=inputs) else:",
"if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png',",
"tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if",
"msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01, msg=msg%'scale error",
"np.array([0, 0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1,",
"None: inputs, results = self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one orig_time",
"delta_q=1e-4, msg=None): if pose0 is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc,",
"fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name,",
"} common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5,",
"RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width,",
"obj = sm.asteroid.real_shape_model obj_idx = re.load_object(obj) light = np.array([1, 0, -0.5]) light /=",
"datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time =",
"import VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam",
"0, -sm.min_med_distance * 0.7]) cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0))",
"image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t",
"setUp(self, verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers':",
"as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results),",
"bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1 msg = '%s deviate(s)",
"(msg + ': norm(%s) %f > %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self,",
"delete=False) tf.close() for i in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br')",
"': norm(%s) %f > %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose,",
"results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed",
"SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _ in inputs: cv2.imshow('t',",
"7.309, # y fov in degrees f_stop=5, # TODO: put better value here",
"import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False,",
"msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too",
"fov in degrees (could be 6 & 5.695, 5.15 & 4.89, 7.7 &",
"def _save_recording(self, fname, inputs, results): tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in",
"'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, #",
"inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)):",
"loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None",
"= cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst",
"common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs",
"on the lens **common_kwargs ) if __name__ == '__main__': import sys if len(sys.argv)",
"Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam()",
"msg=None if msg is None else (msg + ': quat %s vs %s'%(pose0.quat,",
"SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _,",
"def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None",
"in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name)",
"'%s deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1, delta_v=0.02, delta_q=1, msg=msg%'estimated",
"5.15 & 4.89, 7.7 & 7.309) 7.309, # y fov in degrees f_stop=5,",
"None else (msg + ': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0,",
"'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range =",
"one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname, inputs, results): tf =",
"fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def",
"Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and pose1 is None: return",
"> 1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1,",
"center pixel scattering_coef=2e-10, # affects strength of haze/veil when sun shines on the",
"msg='estimated pose deviates too much from the real one') if record: self._save_recording(pickle_file, inputs,",
"haze/veil when sun shines on the lens **common_kwargs ) if __name__ == '__main__':",
"24, } self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self):",
"record and results is None: inputs, results = self._load_recording(pickle_file) else: results = []",
"delta_v=0.02, delta_q=1, msg=msg%'estimated poses') self.assertArrayAlmostEqual(bias_sds0, bias_sds1, delta=0.1, ord=np.inf, msg=msg%'error estimates') self.assertAlmostEqual(scale_sd0, scale_sd1, delta=0.01,",
"None and results is None if not record and results is None: inputs,",
"and quat1 is None: return diff = math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None",
"visnav.render.render import RenderEngine from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re",
"Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def",
"len(sys.argv) > 1 and sys.argv[1] == 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos",
"self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None else (msg + ': quat",
"point_spread_fn=0.50, # ratio of brightness in center pixel scattering_coef=2e-10, # affects strength of",
"cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior, cam_q)",
"cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False)",
"0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max':",
"7.309) 7.309, # y fov in degrees f_stop=5, # TODO: put better value",
"inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with",
"strength of haze/veil when sun shines on the lens **common_kwargs ) if __name__",
"= math.degrees(tools.angle_between_q(quat0, quat1)) self.assertAlmostEqual(0, diff, delta=delta, msg=None if msg is None else (msg",
"test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not",
"* 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior, cam_q) if record:",
"pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is not None and results",
"inputs, results = self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one orig_time =",
"inputs.append([image, cam_ast_cv_v, cam_ast_cv_q]) if 0: for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image,",
"params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo = VisualOdometry(self.cam,",
"# TODO: put better value here point_spread_fn=0.50, # ratio of brightness in center",
"# affects strength of haze/veil when sun shines on the lens **common_kwargs )",
"for i in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name,",
"common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e':",
"here point_spread_fn=0.50, # ratio of brightness in center pixel scattering_coef=2e-10, # affects strength",
"in range(len(inputs)): cv2.imwrite(tf.name, inputs[i][0], (cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0] =",
"with open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as",
"'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9,",
"= datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time",
"None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg",
"arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None and arr1 is None:",
"& 5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309, # y fov in",
"height in pixels 7.7, # x fov in degrees (could be 6 &",
"'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera( 2048, # width",
"pickle import tempfile import os import math from datetime import datetime import numpy",
"quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for i in",
"return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if msg is None else (msg +",
"is None: inputs, results = self._load_recording(pickle_file) else: results = [] cam_q = quaternion.one",
"results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022,",
"tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0])",
"prior, cam_q) if record: results.append(res) elif 0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1",
"pass def get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944 * 0.0022),",
"1 and sys.argv[1] == 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel",
"results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False) tf.close() for i in range(len(inputs)): with",
"= np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None else (msg",
"is None: return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg",
"(diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7, ord=np.inf, msg=None): if arr0 is None",
"result1 msg = '%s deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0, pose1,",
"class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist': 10,",
"sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, }",
"# snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40,",
"pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None else (msg + ':",
"} self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass",
"(cv2.IMWRITE_PNG_COMPRESSION, 9)) with open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname,",
"with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs,",
"much from the real one') if record: self._save_recording(pickle_file, inputs, results) def _save_recording(self, fname,",
"= quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for i",
"from visnav.settings import * sm = DidymosSystemModel(use_narrow_cam=False, target_primary=False, hi_res_shape_model=True) re = RenderEngine(sm.cam.width, sm.cam.height,",
"fh) def _load_recording(self, fname): with open(fname, 'rb') as fh: inputs, results = pickle.load(fh)",
"(could be 6 & 5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309, #",
"degrees (could be 6 & 5.695, 5.15 & 4.89, 7.7 & 7.309) 7.309,",
"when sun shines on the lens **common_kwargs ) if __name__ == '__main__': import",
"os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass def get_cam(): common_kwargs_worst = { 'sensor_size':",
"result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1 msg =",
"%f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4,",
"= result1 msg = '%s deviate(s) too much from the expected value(s)' self.assertPoseAlmostEqual(pose0,",
"delta_v=0.1, delta_q=10, msg='estimated pose deviates too much from the real one') if record:",
"open(tf.name, 'br') as fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh:",
"'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu)",
"better value here point_spread_fn=0.50, # ratio of brightness in center pixel scattering_coef=2e-10, #",
"= inputs is not None and results is None if not record and",
"os import math from datetime import datetime import numpy as np import quaternion",
"fh: fh.write(inputs[i][0]) inputs[i][0] = cv2.imread(tf.name, cv2.IMREAD_GRAYSCALE) os.unlink(tf.name) return inputs, results def get_rot_imgs(): pass",
"pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and pose1",
"40, 'dark_noise_sd': 6.32, 'readout_noise_sd': 15, # dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, #",
"return norm = np.linalg.norm(np.array(arr0)-np.array(arr1), ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None",
"with open(fname, 'rb') as fh: inputs, results = pickle.load(fh) tf = tempfile.NamedTemporaryFile(suffix='.png', delete=False)",
"cam_ast_q0 = quaternion.one dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for",
"in pixels 1944, # height in pixels 7.7, # x fov in degrees",
"20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd': 6.32, 'readout_noise_sd':",
"unittest import pickle import tempfile import os import math from datetime import datetime",
"the lens **common_kwargs ) if __name__ == '__main__': import sys if len(sys.argv) >",
"from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from",
"= np.array([1, 0, -0.5]) light /= np.linalg.norm(light) cam_ast_v0 = np.array([0, 0, -sm.min_med_distance *",
"= 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4,",
"and results is None if not record and results is None: inputs, results",
"i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs): time = datetime.fromtimestamp(orig_time + i*60) prior =",
"(2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max =",
"fh: inputs[i][0] = fh.read() os.unlink(tf.name) with open(fname, 'wb') as fh: pickle.dump((inputs, results), fh)",
"**params) def tearDown(self): pass def assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is",
"tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for i in range(60): cam_ast_v =",
"to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose deviates too much",
"cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v,",
"prior = Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img,",
"dq = tools.angleaxis_to_q((math.radians(1), 0, 1, 0)) inputs = [] for i in range(60):",
"get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image,",
"is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v, ord=2, msg=None if",
"= Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time,",
"verbose=False): self.cam = get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24,",
"0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior, cam_q) if record: results.append(res)",
"sys.argv[1] == 'record': from visnav.algo.model import SystemModel from visnav.missions.didymos import DidymosSystemModel from visnav.render.render",
"2048, # width in pixels 1944, # height in pixels 7.7, # x",
"'wb') as fh: pickle.dump((inputs, results), fh) def _load_recording(self, fname): with open(fname, 'rb') as",
"'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x': 55, 'exclusion_angle_y': 90, } common_kwargs_best",
"1, 0)) inputs = [] for i in range(60): cam_ast_v = cam_ast_v0 cam_ast_q",
"is None else (msg + ': loc %s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat,",
"assertQuatAlmostEqual(self, quat0, quat1, delta=1e-4, msg=None): if quat0 is None and quat1 is None:",
"%s vs %s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None else",
"put better value here point_spread_fn=0.50, # ratio of brightness in center pixel scattering_coef=2e-10,",
"get_cam(): common_kwargs_worst = { 'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30,",
"ord=ord) self.assertAlmostEqual(0, norm, delta=delta, msg=None if msg is None else (msg + ':",
"5, }) common_kwargs = common_kwargs_best return Camera( 2048, # width in pixels 1944,",
"snr_max = 20*log10(sqrt(sat_e)) dB 'lambda_min': 350e-9, 'lambda_eff': 580e-9, 'lambda_max': 800e-9, 'dark_noise_mu': 40, 'dark_noise_sd':",
"else (msg + ': angle[deg] %f > %f' % (diff, delta))) def assertArrayAlmostEqual(self,",
"if msg is None else (msg + ': quat %s vs %s'%(pose0.quat, pose1.quat)))",
"0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, # snr_max = 20*log10(sqrt(sat_e)) dB",
"common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd':",
"y fov in degrees f_stop=5, # TODO: put better value here point_spread_fn=0.50, #",
"> %f' % (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7,",
") if __name__ == '__main__': import sys if len(sys.argv) > 1 and sys.argv[1]",
"is not None and results is None if not record and results is",
"assertOdomResultAlmostEqual(self, result0, result1): pose0, bias_sds0, scale_sd0 = result0 pose1, bias_sds1, scale_sd1 = result1",
"error estimate') def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record =",
"55, 'exclusion_angle_y': 90, } common_kwargs_best = dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu':",
"+ ': angle[deg] %f > %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1,",
"results is None: inputs, results = self._load_recording(pickle_file) else: results = [] cam_q =",
"self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose",
"np import quaternion import cv2 from visnav.algo.model import Camera from visnav.algo.odometry import VisualOdometry,",
"of brightness in center pixel scattering_coef=2e-10, # affects strength of haze/veil when sun",
"delta_v=1e-7, delta_q=1e-4, msg=None): if pose0 is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc,",
"5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return Camera( 2048, # width in",
"* cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q, light, gamma=1.8, get_depth=False) cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q,",
"'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, }) common_kwargs = common_kwargs_best return",
"delete=False) tf.close() for i in range(len(inputs)): with open(tf.name, 'wb') as fh: fh.write(inputs[i][0]) inputs[i][0]",
"results = [] cam_q = quaternion.one orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for",
"in range(60): cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx,",
"visnav.missions.didymos import DidymosSystemModel from visnav.render.render import RenderEngine from visnav.settings import * sm =",
"0: self.assertOdomResultAlmostEqual(results[i], res) if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to get",
"if len(sys.argv) > 1 and sys.argv[1] == 'record': from visnav.algo.model import SystemModel from",
"orig_time = datetime.strptime('2020-07-01 15:42:00', '%Y-%m-%d %H:%M:%S').timestamp() for i, (img, cam_obj_v, cam_obj_q) in enumerate(inputs):",
"res) if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate')",
"TODO: put better value here point_spread_fn=0.50, # ratio of brightness in center pixel",
"{ 'sensor_size': (2048 * 0.0022, 1944 * 0.0022), 'quantum_eff': 0.30, 'px_saturation_e': 2200, #",
"1944, # height in pixels 7.7, # x fov in degrees (could be",
"%s'%(pose0.loc, pose1.loc))) self.assertQuatAlmostEqual(pose0.quat, pose1.quat, delta=delta_q, msg=None if msg is None else (msg +",
"scattering_coef=2e-10, # affects strength of haze/veil when sun shines on the lens **common_kwargs",
"0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior, res[0], delta_v=0.1, delta_q=10, msg='estimated pose",
"if i > 1 and 0: self.assertIsNotNone(res[0], msg='failed to get pose estimate') self.assertPoseAlmostEqual(prior,",
"def test_rotating_object(self, inputs=None, results=None): pickle_file = os.path.join(os.path.dirname(__file__), 'data', 'test_rotating_object.pickle') record = inputs is",
"scale_sd1 = result1 msg = '%s deviate(s) too much from the expected value(s)'",
"% (ord, norm, delta))) def assertPoseAlmostEqual(self, pose0: Pose, pose1: Pose, delta_v=1e-7, delta_q=1e-4, msg=None):",
"if 0: for image, _, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5))",
"else (msg + ': quat %s vs %s'%(pose0.quat, pose1.quat))) def assertOdomResultAlmostEqual(self, result0, result1):",
"self.odo = VisualOdometry(self.cam, self.cam.width/4, verbose=verbose, pause=False, use_scale_correction=False, est_cam_pose=False, **params) def tearDown(self): pass def",
"get_cam() params = { 'min_keypoint_dist': 10, 'min_inliers': 12, 'min_2d2d_inliers': 24, } self.odo =",
"# dark_noise_sd should be sqrt(dark_noise_mu) 'emp_coef': 1, # dynamic range = 20*log10(sat_e/readout_noise)) 'exclusion_angle_x':",
"_, _ in inputs: cv2.imshow('t', cv2.resize(image, None, fx=0.5, fy=0.5)) cv2.waitKey() else: t =",
"cam_ast_v = cam_ast_v0 cam_ast_q = dq**i * cam_ast_q0 image = re.render(obj_idx, cam_ast_v, cam_ast_q,",
"VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase): def setUp(self, verbose=False): self.cam =",
"tempfile import os import math from datetime import datetime import numpy as np",
"Pose(cam_obj_v, cam_obj_q, np.ones((3,)) * 0.1, np.ones((3,)) * 0.01) res = self.odo.process(img, time, prior,",
"dict(common_kwargs_worst) common_kwargs_best.update({ 'quantum_eff': 0.4, 'px_saturation_e': 3500, 'dark_noise_mu': 25, 'dark_noise_sd': 5, 'readout_noise_sd': 5, })",
"__name__ == '__main__': import sys if len(sys.argv) > 1 and sys.argv[1] == 'record':",
"': angle[deg] %f > %f' % (diff, delta))) def assertArrayAlmostEqual(self, arr0, arr1, delta=1e-7,",
"import Camera from visnav.algo.odometry import VisualOdometry, Pose from visnav.algo import tools class TestOdometry(unittest.TestCase):",
"msg=None): if pose0 is None and pose1 is None: return self.assertArrayAlmostEqual(pose0.loc, pose1.loc, delta=delta_v,",
"cam_ast_cv_v = tools.q_times_v(SystemModel.cv2gl_q, cam_ast_v) cam_ast_cv_q = SystemModel.cv2gl_q * cam_ast_q * SystemModel.cv2gl_q.conj() inputs.append([image, cam_ast_cv_v,"
] |
[
"\": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\":",
"\"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React",
"channel.send(message.author.display_name + \" posted in \" + \"Channel **\" + message.channel.name + \"**:\\n\"",
"Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications',",
"{ \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to",
"channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We",
"\"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\",",
"\"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this message",
"\": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \":",
"async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message =",
"to accept being pinged by anybody at any time (Non-Notification based pings)': {",
"None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else:",
"slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\",",
"for pattern in exceptions: result = re.search(pattern, str) if result and matched ==",
"\"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only',",
"str.replace(replacer, replace[replacer]) matched = False match = 0 for pattern in bad_word: result",
"in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command()",
"match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \"",
"\"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\",",
"this message with the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡",
"def prime_reactions(ctx): if ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete()",
"from discord.ext import commands from discord.utils import get import re bot = commands.Bot(command_prefix=\"!\")",
"dnspython import server from discord.ext import commands from discord.utils import get import re",
"\"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\",",
"async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message):",
"with: \" + pattern) if matched == True and match != 0: channel",
"'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this message",
"\": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \":",
"in \" + \"Channel **\" + message.channel.name + \"**:\\n\" + message.content ) await",
"slur \"fa+g\", #f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\",",
"await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role",
"with the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name",
"bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \" + \"Channel **\" + message.channel.name",
"True and match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted",
"Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\":",
"\"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\",",
"\"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React",
"!= channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await",
"payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary =",
"\"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c",
"role = None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles,",
"+= 1 print(\"Matched with: \" + pattern) for pattern in exceptions: result =",
"ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in",
"\"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\",",
"\"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫",
"\"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word",
"None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for",
"message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if",
"He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\":",
"pynacl #import dnspython import server from discord.ext import commands from discord.utils import get",
"roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for",
"'React to this message with a ✅ to accept being pinged by anybody",
"\" posted in \" + \"Channel **\" + message.channel.name + \"**:\\n\" + message.content",
"for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They',",
"\"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\"",
"message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check",
"with: \" + pattern) for pattern in exceptions: result = re.search(pattern, str) if",
"\"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\",",
"def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await",
"pinged by anybody at any time (Non-Notification based pings)': { \"✅\": 'Accept Pings'",
"message.content in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys():",
"match += 1 print(\"Matched with: \" + pattern) for pattern in exceptions: result",
"TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\":",
"by anybody at any time (Non-Notification based pings)': { \"✅\": 'Accept Pings' }",
"0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \" + \"Channel",
"role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command() async def",
"await channel.send('Channel **' + ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await ctx.message.delete()",
"ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in",
"ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in role_type_dictionary[ref_message.content].keys(): await ref_message.add_reaction(emoji_check)",
"#t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions =",
"role != None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]:",
"message.content ) await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id !=",
"user = payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None",
"{ 'React to this message with the notification roles you would like.\\n🔴 Youtube",
"+ ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def",
"\": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \":",
"+ str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference == None: return",
"\"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word =",
"channel.send('Channel **' + ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command()",
"@bot.event async def on_message(message): if message.author == bot.user: return str = message.content for",
"role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role != None:",
"to this message with the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚",
"= bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '** ID: ' + str(ctx.channel.id))",
"= re.search(pattern, str) if result: matched = True match += 1 print(\"Matched with:",
"<filename>bot/main.py import discord import os #import pynacl #import dnspython import server from discord.ext",
"\": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\":",
"\"fa+g\", #f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\",",
"exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\",",
"She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\":",
"Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement",
"\"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳",
"channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user =",
"result = re.search(pattern, str) if result: matched = True match += 1 print(\"Matched",
"+ pattern) for pattern in exceptions: result = re.search(pattern, str) if result and",
"await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in role_type_dictionary[ref_message.content].keys(): await",
"bot.user: return str = message.content for replacer in replace.keys(): str = str.replace(replacer, replace[replacer])",
"\": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\",",
"== True and match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \"",
"if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await",
"like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream",
"\"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary =",
"\"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\"",
"0 for pattern in bad_word: result = re.search(pattern, str) if result: matched =",
"\"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions",
"\"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦",
"\"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t",
"#wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur",
"user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role =",
"result and matched == True: match -= 1 print(\"Unmatched with: \" + pattern)",
"'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React to this message with a",
"= commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\":",
"1 print(\"Matched with: \" + pattern) for pattern in exceptions: result = re.search(pattern,",
"!= 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \" +",
"'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' },",
"\"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\",",
"message.author == bot.user: return str = message.content for replacer in replace.keys(): str =",
"\"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧",
"str) if result and matched == True: match -= 1 print(\"Unmatched with: \"",
"matched == True: match -= 1 print(\"Unmatched with: \" + pattern) if matched",
"None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if",
"\"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f",
"} @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async",
"\": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \":",
"in exceptions: result = re.search(pattern, str) if result and matched == True: match",
"\"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\",",
"logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return",
"bad_word: result = re.search(pattern, str) if result: matched = True match += 1",
"commands from discord.utils import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\")",
"\"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this message with the",
"Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They',",
"'** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference",
"\": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \":",
"pattern) for pattern in exceptions: result = re.search(pattern, str) if result and matched",
"Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications'",
"would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\":",
"\": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \":",
"\"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\",",
"\"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸",
"Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React",
"#chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d",
"} bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur",
"bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id)",
"\": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \":",
"user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id)",
"emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role)",
"server from discord.ext import commands from discord.utils import get import re bot =",
"if role != None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev'])",
"get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '** ID: '",
"951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We have logged in as",
"#import dnspython import server from discord.ext import commands from discord.utils import get import",
"role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role != None: await",
"discord.ext import commands from discord.utils import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN",
"\"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬",
"}, 'React to this message with a ✅ to accept being pinged by",
"{ \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\",",
"\"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\",",
"\"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\":",
"\"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \":",
"\"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\",",
"and match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in",
"get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role) @bot.event",
"\": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \":",
"#import pynacl #import dnspython import server from discord.ext import commands from discord.utils import",
"re.search(pattern, str) if result and matched == True: match -= 1 print(\"Unmatched with:",
"{ \"✅\": 'Accept Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004",
"@bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name +",
"import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\",",
"}, 'React to this message with the gender roles you identify as.\\n❤️ He/Him\\n🧡",
"\"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions = { \"retardant\",",
"+ message.channel.name + \"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message) @bot.event async",
"{ \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name",
"+ \" posted in \" + \"Channel **\" + message.channel.name + \"**:\\n\" +",
"as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return str =",
"anybody at any time (Non-Notification based pings)': { \"✅\": 'Accept Pings' } }",
"\"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶",
"\"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = {",
"in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role !=",
"= os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\",",
"the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': {",
"at any time (Non-Notification based pings)': { \"✅\": 'Accept Pings' } } channels",
"replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False match = 0 for pattern",
"you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns':",
"in replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False match = 0 for",
"#shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\",",
"\"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this",
"{ \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\",",
"def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await",
"\"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r",
"\"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\",",
"bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role",
"message with the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜",
"\"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\",",
"identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': {",
"exceptions: result = re.search(pattern, str) if result and matched == True: match -=",
"= { 'React to this message with the notification roles you would like.\\n🔴",
"import os #import pynacl #import dnspython import server from discord.ext import commands from",
"@bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message",
"'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for",
"\"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾",
"on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author",
"+ message.content ) await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id",
"He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him',",
"user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name",
"Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this message with",
"os #import pynacl #import dnspython import server from discord.ext import commands from discord.utils",
"commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\",",
"to this message with a ✅ to accept being pinged by anybody at",
"guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content",
"\"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\",",
"958468714846634004 } @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event",
"matched = True match += 1 print(\"Matched with: \" + pattern) for pattern",
"\": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \":",
"channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role =",
"pattern in exceptions: result = re.search(pattern, str) if result and matched == True:",
"\"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\",",
"str = message.content for replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched =",
"payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild =",
"\"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\",",
"\"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻",
"\"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot))",
"\"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\",",
"in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return str",
"\"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner",
"+ \"Channel **\" + message.channel.name + \"**:\\n\" + message.content ) await message.delete() await",
"async def on_message(message): if message.author == bot.user: return str = message.content for replacer",
"for replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False match =",
"\"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g",
"replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\",",
"role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await",
"role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None:",
"= bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if",
"\"y\" } bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c",
"\"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\":",
"\"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷",
"ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference == None: return ref_message = await",
"= role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check,",
"import discord import os #import pynacl #import dnspython import server from discord.ext import",
"\"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\",",
") await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]:",
"= { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback",
"'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this message with the gender",
"Only', \"🤍\": 'Ask for Pronouns' }, 'React to this message with a ✅",
"notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\":",
"async def prime_reactions(ctx): if ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await",
"for pattern in bad_word: result = re.search(pattern, str) if result: matched = True",
"message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel",
"import server from discord.ext import commands from discord.utils import get import re bot",
"name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel =",
"\"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵",
"\"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" }",
"\"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\",",
"= await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None",
"return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check =",
"if message.author == bot.user: return str = message.content for replacer in replace.keys(): str",
"\": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \":",
"guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary =",
"gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask",
"channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \" + \"Channel **\"",
"\": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \":",
"\"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱",
"'Ask for Pronouns' }, 'React to this message with a ✅ to accept",
"\"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this message with the notification",
"str = str.replace(replacer, replace[replacer]) matched = False match = 0 for pattern in",
"await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in role_type_dictionary[ref_message.content].keys(): await ref_message.add_reaction(emoji_check) server.server()",
"slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions = {",
"\"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\",",
"\"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" }",
"this message with the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙",
"on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id)",
"None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **'",
"\"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\":",
"being pinged by anybody at any time (Non-Notification based pings)': { \"✅\": 'Accept",
"await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel =",
"if matched == True and match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name",
"based pings)': { \"✅\": 'Accept Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626,",
"\"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \":",
"\": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \":",
"'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React to this message",
"\"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯",
"os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\":",
"\"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\":",
"pattern in bad_word: result = re.search(pattern, str) if result: matched = True match",
"+ pattern) if matched == True and match != 0: channel = bot.get_channel(channels['bot-dev'])",
"\" + pattern) if matched == True and match != 0: channel =",
"\"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹",
"== True: match -= 1 print(\"Unmatched with: \" + pattern) if matched ==",
"if ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content",
"**' + ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async",
"\"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\",",
"role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command() async",
"role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role =",
"Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\":",
"#r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\",",
"\"Channel **\" + message.channel.name + \"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message)",
"prime_reactions(ctx): if ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if",
"= 0 for pattern in bad_word: result = re.search(pattern, str) if result: matched",
"\"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur",
"\"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\",",
"str) if result: matched = True match += 1 print(\"Matched with: \" +",
"+ \"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload):",
"role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user)",
"get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel",
"return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check",
"in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role",
"def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '** ID:",
"await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys():",
"matched = False match = 0 for pattern in bad_word: result = re.search(pattern,",
"!= None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return",
"'Accept Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event",
"str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference == None: return ref_message",
"True: match -= 1 print(\"Unmatched with: \" + pattern) if matched == True",
"def on_message(message): if message.author == bot.user: return str = message.content for replacer in",
"\": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \":",
"channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '** ID: ' +",
"\"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\",",
"message with a ✅ to accept being pinged by anybody at any time",
"= await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in role_type_dictionary[ref_message.content].keys():",
"\"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this",
"== None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id) await ctx.message.delete() if ref_message.content in role_type_dictionary.keys():",
"if result and matched == True: match -= 1 print(\"Unmatched with: \" +",
"'React to this message with the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛",
"pings)': { \"✅\": 'Accept Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\":",
"\"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = {",
"(Non-Notification based pings)': { \"✅\": 'Accept Pings' } } channels = { \"🔔-assign-roles\":",
"\"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r slur",
"#f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\",",
"\"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this message with the notification roles",
"= { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\",",
"= message.content for replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False",
"if result: matched = True match += 1 print(\"Matched with: \" + pattern)",
"bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if message.content",
"\"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴",
"\"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React to this",
"\"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\",",
"= None role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check])",
"= True match += 1 print(\"Matched with: \" + pattern) for pattern in",
"get import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\":",
"Pronouns' }, 'React to this message with a ✅ to accept being pinged",
"role != None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await",
"\"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪",
"#beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale",
"you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications',",
"+ '** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if",
"\"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\",",
"\"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\",",
"\"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\",",
"if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild",
"\"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰",
"name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role) @bot.event async",
"} channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready():",
"\"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲",
"!= channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member",
"\"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\",",
"import commands from discord.utils import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN =",
"discord import os #import pynacl #import dnspython import server from discord.ext import commands",
"\"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\":",
"ctx.message.delete() if ref_message.content in role_type_dictionary.keys(): for emoji_check in role_type_dictionary[ref_message.content].keys(): await ref_message.add_reaction(emoji_check) server.server() bot.run(TOKEN)",
"slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur \"tra+n+y\",",
"\"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\",",
"False match = 0 for pattern in bad_word: result = re.search(pattern, str) if",
"any time (Non-Notification based pings)': { \"✅\": 'Accept Pings' } } channels =",
"a ✅ to accept being pinged by anybody at any time (Non-Notification based",
"await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary",
"\"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\",",
"def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if",
"channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if",
"\"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\",",
"ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx):",
"} role_type_dictionary = { 'React to this message with the notification roles you",
"in bad_word: result = re.search(pattern, str) if result: matched = True match +=",
"emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content]",
"this message with a ✅ to accept being pinged by anybody at any",
"await channel.send(message.author.display_name + \" posted in \" + \"Channel **\" + message.channel.name +",
"= re.search(pattern, str) if result and matched == True: match -= 1 print(\"Unmatched",
"slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\",",
"re.search(pattern, str) if result: matched = True match += 1 print(\"Matched with: \"",
"bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id)",
"'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React to",
"{ \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\",",
"posted in \" + \"Channel **\" + message.channel.name + \"**:\\n\" + message.content )",
"\"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to",
"\"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n",
"role_type_dictionary = { 'React to this message with the notification roles you would",
"\"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns' }, 'React to this message with",
"1 print(\"Unmatched with: \" + pattern) if matched == True and match !=",
"#n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur",
"**\" + message.channel.name + \"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message) @bot.event",
"matched == True and match != 0: channel = bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name +",
"slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese",
"\"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\":",
"\"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽",
"bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\",",
"= False match = 0 for pattern in bad_word: result = re.search(pattern, str)",
"\": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \":",
"return str = message.content for replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched",
"== bot.user: return str = message.content for replacer in replace.keys(): str = str.replace(replacer,",
"= await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check =",
"#d slur \"fa+g\", #f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\",",
"\"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\",",
"@bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def",
"= await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys():",
"await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' +",
"= { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We have",
"async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '**",
"= get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role)",
"return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user",
"await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference == None: return ref_message =",
"They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her',",
"' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference == None:",
"\"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\",",
"= payload.member emoji_check = str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary",
"pattern) if matched == True and match != 0: channel = bot.get_channel(channels['bot-dev']) await",
"for Pronouns' }, 'React to this message with a ✅ to accept being",
"message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji) if message.content in",
"as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\":",
"slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\",",
"\"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭 \": \"h\", \"🇮",
"\"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\":",
"True match += 1 print(\"Matched with: \" + pattern) for pattern in exceptions:",
"\"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\",",
"match = 0 for pattern in bad_word: result = re.search(pattern, str) if result:",
"match -= 1 print(\"Unmatched with: \" + pattern) if matched == True and",
"\"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \": \"r\",",
"\"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\",",
"\" + pattern) for pattern in exceptions: result = re.search(pattern, str) if result",
"replace[replacer]) matched = False match = 0 for pattern in bad_word: result =",
"channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check = str(payload.emoji)",
"\"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask",
"with the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications':",
"role_dictionary = role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role",
"\"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\",",
"\"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\",",
"c slur \"g[yi]psy\", #g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur",
"ID: ' + str(ctx.channel.id)) await ctx.message.delete() @bot.command() async def prime_reactions(ctx): if ctx.message.reference ==",
"\"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿",
"await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel =",
"re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = { \"\\\\|3\": \"b\", \"/\\\\\\\\\":",
"if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user",
"\"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\",",
"\": \"g\", \"🇭 \": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \":",
"\"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\",",
"Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\":",
"= bot.get_channel(channels['bot-dev']) await channel.send(message.author.display_name + \" posted in \" + \"Channel **\" +",
"channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user = payload.member emoji_check",
"Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' },",
"str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if emoji_check",
"\"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼",
"= { \"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\":",
"= str.replace(replacer, replace[replacer]) matched = False match = 0 for pattern in bad_word:",
"the gender roles you identify as.\\n❤️ He/Him\\n🧡 She/Her\\n💛 They/Them\\n💚 He/They\\n💙 She/They\\n💜 Name Only\\n🤍",
"\"🇶 \": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺",
"on_message(message): if message.author == bot.user: return str = message.content for replacer in replace.keys():",
"\": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \":",
"bot.get_channel(channels['bot-dev']) await channel.send('Channel **' + ctx.channel.name + '** ID: ' + str(ctx.channel.id)) await",
"\"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨",
"\"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We have logged in",
"\": \"q\", \"🇷 \": \"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \":",
"\"✅\": 'Accept Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 }",
"await message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload):",
"\"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\": \"qu\", \"wh\": \"h\", \"uh\": \"a\",",
"message.channel.name + \"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message) @bot.event async def",
"await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji)",
"Notifications' }, 'React to this message with the gender roles you identify as.\\n❤️",
"#g slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur",
"\"qu\", \"wh\": \"h\", \"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \":",
"print(\"Matched with: \" + pattern) for pattern in exceptions: result = re.search(pattern, str)",
"if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if",
"@bot.command() async def prime_reactions(ctx): if ctx.message.reference == None: return ref_message = await ctx.channel.fetch_message(ctx.message.reference.message_id)",
"\"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\": \"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\":",
"Pings' } } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async",
"\"uh\": \"a\", \"pe\": \"p\", \"p3\": \"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \":",
"} } channels = { \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def",
"\"i\", \"[0ôöòó•Ø]\": \"o\", \"[z5$§]\":\"s\", \"[%+7]\":\"t\", \"[üûùúµ]\":\"u\", \"[ÿ¥µŸý]\": \"y\" } bad_word = { \"re+ta+rd\",",
"payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) user =",
"have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user:",
"\"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\": 'Ask for Pronouns'",
"\"🤍\": 'Ask for Pronouns' }, 'React to this message with a ✅ to",
"result = re.search(pattern, str) if result and matched == True: match -= 1",
"= bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) user = await",
"bad_word = { \"re+ta+rd\", #r slur \"ni+g+[eau]r?\", #n slur \"[qck]o+o+n\", #c slur \"we+tba+[qck]\",",
"time (Non-Notification based pings)': { \"✅\": 'Accept Pings' } } channels = {",
"= str(payload.emoji) if message.content in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if",
"\"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \": \"f\", \"🇬 \": \"g\", \"🇭",
"\"t\", \"🇺 \": \"u\", \"🇻 \": \"v\", \"🇼 \": \"w\", \"🇽 \": \"x\",",
"Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this message with the gender roles",
"message.content for replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False match",
"She/They\\n💜 Name Only\\n🤍 Ask for Pronouns': { \"❤️\": 'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them',",
"async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message =",
"print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author ==",
"\" + \"Channel **\" + message.channel.name + \"**:\\n\" + message.content ) await message.delete()",
"to this message with the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream",
"\": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\",",
"else: await message.remove_reaction(emoji_check, user) if role != None: await user.add_roles(role) @bot.event async def",
"\": \"n\", \"🇴 \": \"o\", \"🇵 \": \"p\", \"🇶 \": \"q\", \"🇷 \":",
"accept being pinged by anybody at any time (Non-Notification based pings)': { \"✅\":",
"\"🟣\": 'Stream Notifications', \"🟡\": 'Announcement Notifications' }, 'React to this message with the",
"= get(user.guild.roles, name=role_dictionary[emoji_check]) if role != None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx):",
"with a ✅ to accept being pinged by anybody at any time (Non-Notification",
"user) if role != None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id",
"\"**:\\n\" + message.content ) await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if",
"!= None: await user.remove_roles(role) @bot.command() async def get_channel_id(ctx): channel = bot.get_channel(channels['bot-dev']) await channel.send('Channel",
"on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id)",
"\"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary = { 'React to this message with",
"\"\\\\|3\": \"b\", \"/\\\\\\\\\": \"a\", \"ph\": \"f\", \"ck\": \"k\", \"zz\": \"s\", \"qw\": \"qu\", \"kw\":",
"channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id)",
"\"r\", \"🇸 \": \"s\", \"🇹 \": \"t\", \"🇺 \": \"u\", \"🇻 \": \"v\",",
"= await bot.fetch_guild(payload.guild_id) user = await guild.fetch_member(payload.user_id) emoji_check = str(payload.emoji) if message.content in",
"\"🟡\": 'Announcement Notifications' }, 'React to this message with the gender roles you",
"\"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\":",
"roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube",
"message with the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣 Stream Notifications\\n🟡 Announcement",
"await message.delete() await bot.process_commands(message) @bot.event async def on_raw_reaction_add(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return",
"if message.content in role_type_dictionary.keys(): role = None role_dictionary = role_type_dictionary[message.content] if emoji_check in",
"'React to this message with the notification roles you would like.\\n🔴 Youtube Notifications\\n🟣",
"discord.utils import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace =",
"\": \"h\", \"🇮 \": \"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \":",
"\"p\", \"nn\": \"n\", \"🇦 \": \"a\", \"🇧 \": \"b\", \"🇨 \": \"c\", \"🇩",
"and matched == True: match -= 1 print(\"Unmatched with: \" + pattern) if",
"= role_type_dictionary[message.content] if emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) if role !=",
"\"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\", \"[68]\": \"b\", \"[瀩]\": \"c\", \"[3êëèæ€]\": \"e\", \"[l1!|ïîìí¡¦]\":",
"@bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel = bot.get_channel(payload.channel_id) message",
"import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace = {",
"\": \"b\", \"🇨 \": \"c\", \"🇩 \": \"d\", \"🇪 \": \"e\", \"🇫 \":",
"slur \"tra+n+y\", #t slur \"she+ma+le\", #shemale \"d[yi]ke\", #d slur \"fa+g\", #f slur }",
"-= 1 print(\"Unmatched with: \" + pattern) if matched == True and match",
"replacer in replace.keys(): str = str.replace(replacer, replace[replacer]) matched = False match = 0",
"Notifications\\n🟣 Stream Notifications\\n🟡 Announcement Notifications': { \"🔴\": 'Youtube Notifications', \"🟣\": 'Stream Notifications', \"🟡\":",
"{0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return str = message.content",
"\"w\", \"🇽 \": \"x\", \"🇾 \": \"y\", \"🇿 \": \"z\", \"¶\":\"p\", \"[@4^âäàåæáã]\": \"a\",",
"'He/Him', \"🧡\": 'She/Her', \"💛\": 'They/Them', \"💚\": 'He/They', \"💙\": 'She/They', \"💜\": 'Name Only', \"🤍\":",
"✅ to accept being pinged by anybody at any time (Non-Notification based pings)':",
"\"i\", \"🇯 \": \"j\", \"🇰 \": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\",",
"\"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\", \"chinquapin\", \"chinch\", \"chincapin\", \"vandyke\", \"klondike\",\"fagin\",\"fage\" } role_type_dictionary",
"if role != None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id !=",
"'Announcement Notifications' }, 'React to this message with the gender roles you identify",
"\"d[yi]ke\", #d slur \"fa+g\", #f slur } exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\",",
"#c slur \"we+tba+[qck]\", #wetback \"be+[ae]n[euar]r\", #beaner \"chi+n[qck]\", #chinese c slur \"g[yi]psy\", #g slur",
"result: matched = True match += 1 print(\"Matched with: \" + pattern) for",
"from discord.utils import get import re bot = commands.Bot(command_prefix=\"!\") TOKEN = os.getenv(\"DISCORD_TOKEN\") replace",
"} exceptions = { \"retardant\", \"rac+oon\",\"cocoon\",\"tycoon\",\"cooncan\", \"puccoon\",\"coontie\", \"coonskin\", \"coonhound\", \"beanery\", \"beaneries\", \"pachinko\", \"chinkapin\",",
"None: await user.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): if payload.channel_id != channels[\"🔔-assign-roles\"]: return channel",
"\": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \": \"o\", \"🇵 \":",
"\": \"k\", \"🇱 \": \"l\", \"🇲 \": \"m\", \"🇳 \": \"n\", \"🇴 \":",
"{ \"🔔-assign-roles\": 951692177086488626, \"bot-dev\": 958468714846634004 } @bot.event async def on_ready(): print('We have logged",
"print(\"Unmatched with: \" + pattern) if matched == True and match != 0:",
"emoji_check in role_dictionary.keys(): role = get(user.guild.roles, name=role_dictionary[emoji_check]) else: await message.remove_reaction(emoji_check, user) if role"
] |
[
"fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss:",
"print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end):",
"time slot of the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times,",
"= wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals",
"freq) vals = wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\" # times",
"freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return vals def main():",
"vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals)",
"= wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2)",
"plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION",
"\"\"\"main function\"\"\" # times is array of values at each time slot of",
"good, but when stitching together with play_n, # there is an audible click.",
"with play_n, # there is an audible click. perhaps due to rounding? #",
"vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ',",
"wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals =",
"= wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals",
"freq) return vals def main(): \"\"\"main function\"\"\" # times is array of values",
"freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq)",
"there is an audible click. perhaps due to rounding? # so for now",
"FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4,",
"vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav',",
"wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals =",
"for now I'm leaving this as the linear scaling to avoid the click...",
"of the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4))",
"vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_up_2x.wav',",
"# times is array of values at each time slot of the whole",
"wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals =",
"import wavelib #import plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0",
"freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times,",
"as the linear scaling to avoid the click... TODO fix it #freq =",
"STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds good, but when",
"= DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds",
"is an audible click. perhaps due to rounding? # so for now I'm",
"= 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP",
"to rounding? # so for now I'm leaving this as the linear scaling",
"def main(): \"\"\"main function\"\"\" # times is array of values at each time",
"wavelib #import plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 #",
"the exponential glissando sounds good, but when stitching together with play_n, # there",
"but when stitching together with play_n, # there is an audible click. perhaps",
"return vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete:",
"2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals,",
"#plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2))",
"= wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start,",
"FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times,",
"exponential glissando sounds good, but when stitching together with play_n, # there is",
"= wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals",
"freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times,",
"print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\"",
"the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times,",
"vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals)",
"1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): #",
"wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals =",
"wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end,",
"', freq) vals = wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\" #",
"FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times,",
"freq_start, freq_end): # the exponential glissando sounds good, but when stitching together with",
"the linear scaling to avoid the click... TODO fix it #freq = wavelib.glissando(times,",
"freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start,",
"vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_up_2x.wav', vals)",
"#plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2))",
"of values at each time slot of the whole wav file times =",
"vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times,",
"TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential glissando",
"= wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return vals",
"= 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def",
"wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return vals def",
"array of values at each time slot of the whole wav file times",
"vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals)",
"return vals def main(): \"\"\"main function\"\"\" # times is array of values at",
"freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals = wavelib.shepardtone(times, freq) return",
"scaling to avoid the click... TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end)",
"vals def main(): \"\"\"main function\"\"\" # times is array of values at each",
"wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav',",
"vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals)",
"FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4,",
"avoid the click... TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq =",
"#freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq)",
"vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals)",
"wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals =",
"FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times,",
"this as the linear scaling to avoid the click... TODO fix it #freq",
"= wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals",
"# the exponential glissando sounds good, but when stitching together with play_n, #",
"vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times,",
"vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times,",
"seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential",
"slot of the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2,",
"wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\" # times is array of",
"2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals,",
"# so for now I'm leaving this as the linear scaling to avoid",
"vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times,",
"wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals =",
"an audible click. perhaps due to rounding? # so for now I'm leaving",
"tone \"\"\" import wavelib #import plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP",
"I'm leaving this as the linear scaling to avoid the click... TODO fix",
"wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2)",
"DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds good,",
"FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2,",
"freq) vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end): freq =",
"#plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4))",
"vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals)",
"# seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end): # the",
"audible click. perhaps due to rounding? # so for now I'm leaving this",
"def shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds good, but when stitching",
"= wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ', freq) vals",
"wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals =",
"is array of values at each time slot of the whole wav file",
"wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2)",
"<reponame>randbrown/PyWaveTools<gh_stars>1-10 \"\"\" Generate shepard tone \"\"\" import wavelib #import plotlib FREQ_A4 = 440.0",
"440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP *",
"freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals =",
"# there is an audible click. perhaps due to rounding? # so for",
"wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2)",
"due to rounding? # so for now I'm leaving this as the linear",
"TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end)",
"values at each time slot of the whole wav file times = wavelib.createtimes(TOTAL_DURATION)",
"linear scaling to avoid the click... TODO fix it #freq = wavelib.glissando(times, freq_start,",
"* STEPS def shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds good, but",
"= wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals",
"= wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\" # times is array",
"so for now I'm leaving this as the linear scaling to avoid the",
"FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION =",
"click... TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start,",
"\"\"\" Generate shepard tone \"\"\" import wavelib #import plotlib FREQ_A4 = 440.0 STEPS",
"freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times,",
"wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return vals",
"times is array of values at each time slot of the whole wav",
"main(): \"\"\"main function\"\"\" # times is array of values at each time slot",
"times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals,",
"the click... TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times,",
"now I'm leaving this as the linear scaling to avoid the click... TODO",
"to avoid the click... TODO fix it #freq = wavelib.glissando(times, freq_start, freq_end) freq",
"shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals",
"function\"\"\" # times is array of values at each time slot of the",
"#import plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds",
"STEPS = 12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS",
"together with play_n, # there is an audible click. perhaps due to rounding?",
"shepard_glissando(times, freq_start, freq_end): # the exponential glissando sounds good, but when stitching together",
"shepard tone \"\"\" import wavelib #import plotlib FREQ_A4 = 440.0 STEPS = 12.0",
"wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals",
"Generate shepard tone \"\"\" import wavelib #import plotlib FREQ_A4 = 440.0 STEPS =",
"\"\"\" import wavelib #import plotlib FREQ_A4 = 440.0 STEPS = 12.0 DURATION_PER_STEP =",
"def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq)",
"click. perhaps due to rounding? # so for now I'm leaving this as",
"freq = wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq)",
"freq_end): # the exponential glissando sounds good, but when stitching together with play_n,",
"whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals)",
"= wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_down_2x.wav', vals) vals",
"', freq) vals = wavelib.shepardtone(times, freq) return vals def shepard_discrete(times, freq_start, freq_end): freq",
"freq) return vals def shepard_discrete(times, freq_start, freq_end): freq = wavelib.discrete(times, freq_start, freq_end, STEPS)",
"= wavelib.normalize(shepard_discrete(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_discrete_up_2x.wav', vals) main()",
"2) wavelib.write_wave_file('output/shepard_glissando_down_2x.wav', vals) vals = wavelib.normalize(shepard_discrete(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals,",
"stitching together with play_n, # there is an audible click. perhaps due to",
"= 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start, freq_end):",
"= wavelib.discrete(times, freq_start, freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return",
"glissando sounds good, but when stitching together with play_n, # there is an",
"leaving this as the linear scaling to avoid the click... TODO fix it",
"file times = wavelib.createtimes(TOTAL_DURATION) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4*2, FREQ_A4)) #plotlib.plot_wave_and_fft(times, vals) vals =",
"12.0 DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times,",
"each time slot of the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals =",
"it #freq = wavelib.glissando(times, freq_start, freq_end) freq = wavelib.glissando_lin(times, freq_start, freq_end) print('gliss: ',",
"freq_start, freq_end, STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return vals def",
"DURATION_PER_STEP = 1.0 # seconds TOTAL_DURATION = DURATION_PER_STEP * STEPS def shepard_glissando(times, freq_start,",
"perhaps due to rounding? # so for now I'm leaving this as the",
"vals) vals = wavelib.normalize(shepard_glissando(times, FREQ_A4, FREQ_A4*2)) #plotlib.plot_wave_and_fft(times, vals) vals = wavelib.play_n(vals, 2) wavelib.write_wave_file('output/shepard_glissando_up_2x.wav',",
"when stitching together with play_n, # there is an audible click. perhaps due",
"play_n, # there is an audible click. perhaps due to rounding? # so",
"at each time slot of the whole wav file times = wavelib.createtimes(TOTAL_DURATION) vals",
"rounding? # so for now I'm leaving this as the linear scaling to",
"vals = wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main function\"\"\" # times is",
"sounds good, but when stitching together with play_n, # there is an audible",
"STEPS) print('discrete: ', freq) vals = wavelib.shepardtone(times, freq) return vals def main(): \"\"\"main"
] |
[
"RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run() if",
"class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run()",
"run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run() if __name__ == '__main__':",
"pass def run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run() if __name__",
"bsmu.vision.app.base import App class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!') app",
"import App class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!') app =",
"<filename>retinal-fundus/src/bsmu/retinal_fundus/app/main.py<gh_stars>1-10 from bsmu.vision.app.base import App class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus!",
"from bsmu.vision.app.base import App class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!')",
"def run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run() if __name__ ==",
"App class RetinalFundusApp(App): pass def run_app(): print('Run, Retinal Fundus! Run!') app = RetinalFundusApp()",
"print('Run, Retinal Fundus! Run!') app = RetinalFundusApp() app.run() if __name__ == '__main__': run_app()"
] |
[
"commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def",
"message = f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat:",
"now if difference.days < 0: check_date = check_date.replace(year=now.year + 1) difference = check_date",
"- показать дни кождения в конференции.\", f\"{example} <id группы> - показать дни рождения",
"+ \")\" if year: bdate_in = bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date)",
"рождений людей в группе или в беседе.\", f\"{example} - показать дни кождения в",
"f\"Дни рождения пользователей в беседе ✨:\\n\" data = [] now = datetime.datetime.today().date() for",
"__init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in group (but",
"1)) difference = check_date - now if difference.days < 0: check_date = check_date.replace(year=now.year",
"f\"{example} - показать дни кождения в конференции.\", f\"{example} <id группы> - показать дни",
"f\"Ваш день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни",
"self.set_description() def set_description(self): example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений",
"import CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", )",
"message = f\"Ваш день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message",
"\"deactivated\" in m: continue try: if m['bdate'].count(\".\") > 1: year = True user_date",
"for users in group (but no more than `max_users_in_group`), for users in conference.\"\"\"",
"оно пусто!\") break members += result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group:",
"+ user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in sorted(data, key=lambda",
"no more than `max_users_in_group`), for users in conference.\"\"\" if not commands: commands =",
"if offset == 0: return await msg.answer(\"Не удалось получить сообщество или оно пусто!\")",
"strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in group (but no more than",
"получить сообщество или оно пусто!\") break members += result[\"items\"] offset += 1000 if",
"(будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in",
"+ m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0]",
"- показать дни рождения пользователей в группу.\"] async def process_message(self, msg): command, argument",
"except ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date +",
"self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей в группе или в беседе.\",",
"\", исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\"",
"birthday for users in group (but no more than `max_users_in_group`), for users in",
"ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year,",
"while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\"",
"= \" (будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if",
"= user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year,",
"check_date = check_date.replace(year=now.year + 1) difference = check_date - now bdate_in = \"",
"try: check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year, 1, 1)",
"self.parse_message(msg) if argument: members = [] offset = 0 while True: result =",
"*commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in group (but no",
"+ \", исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\"",
"беседе ✨:\\n\" data = [] now = datetime.datetime.today().date() for m in members: if",
"удалось получить сообщество или оно пусто!\") break members += result[\"items\"] offset += 1000",
"= (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for",
"else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date",
"1) - datetime.date(user_date.year, 1, 1)) difference = check_date - now if difference.days <",
"difference = check_date - now if difference.days < 0: check_date = check_date.replace(year=now.year +",
"f\"Вывод дней рождений людей в группе или в беседе.\", f\"{example} - показать дни",
"дни рождения пользователей в группу.\"] async def process_message(self, msg): command, argument = self.parse_message(msg)",
"f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members =",
"\"\"\"Answers with birthday for users in group (but no more than `max_users_in_group`), for",
"not result or \"items\" not in result or not result[\"items\"]: if offset ==",
"конференции.\", f\"{example} <id группы> - показать дни рождения пользователей в группу.\"] async def",
"\" \" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message",
"conference.\"\"\" if not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group =",
"= datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError:",
"🌍 \" + m[\"first_name\"] + \" \" + m[\"last_name\"] + \": \" +",
"пользователей\") break message = f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if",
"if year: bdate_in = bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) + 1,",
"показана лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни рождения пользователей в группе",
"= 0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result",
"+= 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком",
"'%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try:",
"strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description = [f\"Дни",
"msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\" not in result or not",
"not result[\"items\"]: if offset == 0: return await msg.answer(\"Не удалось получить сообщество или",
"now bdate_in = \" (будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) +",
"await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else: members = await",
"data.append((\" 🌍 \" + m[\"first_name\"] + \" \" + m[\"last_name\"] + \": \"",
"plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False,",
"в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\")",
"async def process_message(self, msg): command, argument = self.parse_message(msg) if argument: members = []",
"handler.base_plugin import CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\",",
"= f\"Ваш день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message =",
"not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\"",
"в группе или в беседе.\", f\"{example} - показать дни кождения в конференции.\", f\"{example}",
"return await msg.answer(\"Не удалось получить сообщество или оно пусто!\") break members += result[\"items\"]",
"users in conference.\"\"\" if not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict)",
"prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description =",
"\"дней\")) + \")\" if year: bdate_in = bdate_in[:-1] + \", исполнится \" +",
"not in m or \"deactivated\" in m: continue try: if m['bdate'].count(\".\") > 1:",
"BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with",
"> 1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False",
"1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"] + \"",
"- datetime.date(user_date.year, 1, 1)) difference = check_date - now if difference.days < 0:",
"{self.max_users_in_group} из пользователей\") break message = f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\"",
"узнать дни рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break",
"пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\")",
"or not result[\"items\"]: if offset == 0: return await msg.answer(\"Не удалось получить сообщество",
"= self.parse_message(msg) if argument: members = [] offset = 0 while True: result",
"1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих",
"= f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members",
"m or \"deactivated\" in m: continue try: if m['bdate'].count(\".\") > 1: year =",
"CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def",
"m['bdate'].count(\".\") > 1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year =",
"False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year) except",
"= [f\"Дни рождения\", f\"Вывод дней рождений людей в группе или в беседе.\", f\"{example}",
"пользователей в беседе ✨:\\n\" data = [] now = datetime.datetime.today().date() for m in",
"✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в",
"in m: continue try: if m['bdate'].count(\".\") > 1: year = True user_date =",
"пусто!\") break members += result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group: await",
"members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else: members",
"msg): command, argument = self.parse_message(msg) if argument: members = [] offset = 0",
"year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date =",
"self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут показана лишь",
"group (but no more than `max_users_in_group`), for users in conference.\"\"\" if not commands:",
"+ m[\"first_name\"] + \" \" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") +",
"<filename>plugins/content/content_birthday.py import datetime from handler.base_plugin import CommandPlugin from utils import plural_form, age class",
"= user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference = check_date",
"result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни",
"\"bdate\" not in m or \"deactivated\" in m: continue try: if m['bdate'].count(\".\") >",
"except ValueError: check_date = user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1))",
"(but no more than `max_users_in_group`), for users in conference.\"\"\" if not commands: commands",
"fields=\"bdate\") if not result or \"items\" not in result or not result[\"items\"]: if",
"= await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в беседе ✨:\\n\" data",
"в беседе.\", f\"{example} - показать дни кождения в конференции.\", f\"{example} <id группы> -",
"plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"]",
"result[\"items\"]: if offset == 0: return await msg.answer(\"Не удалось получить сообщество или оно",
"check_date.replace(year=now.year + 1) difference = check_date - now bdate_in = \" (будет через",
"fields=\"bdate\") message = f\"Дни рождения пользователей в беседе ✨:\\n\" data = [] now",
"\"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"] + \" \" + m[\"last_name\"]",
"дни рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message",
"if \"bdate\" not in m or \"deactivated\" in m: continue try: if m['bdate'].count(\".\")",
"year: bdate_in = bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) + 1, (\"год\",",
"\": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in",
"bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in sorted(data, key=lambda x: x[1])) return",
"import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None,",
"def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in group",
"msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id,",
"m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for",
"= f\"Дни рождения пользователей в беседе ✨:\\n\" data = [] now = datetime.datetime.today().date()",
"0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or",
"if not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group",
"import datetime from handler.base_plugin import CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin):",
"bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) +",
"+ 1) difference = check_date - now bdate_in = \" (будет через \"",
"members = [] offset = 0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset,",
"await msg.answer(\"Не удалось получить сообщество или оно пусто!\") break members += result[\"items\"] offset",
"check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year, 1, 1) -",
"== 0: return await msg.answer(\"Не удалось получить сообщество или оно пусто!\") break members",
"кождения в конференции.\", f\"{example} <id группы> - показать дни рождения пользователей в группу.\"]",
"в конференции.\", f\"{example} <id группы> - показать дни рождения пользователей в группу.\"] async",
"self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description = [f\"Дни рождения\",",
"with birthday for users in group (but no more than `max_users_in_group`), for users",
"\" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in = bdate_in[:-1]",
"группе или в беседе.\", f\"{example} - показать дни кождения в конференции.\", f\"{example} <id",
"группу.\"] async def process_message(self, msg): command, argument = self.parse_message(msg) if argument: members =",
"`max_users_in_group`), for users in conference.\"\"\" if not commands: commands = (\"дни рождения\",) super().__init__(*commands,",
"= self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей в группе или",
"msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из",
"from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self,",
"людей в группе или в беседе.\", f\"{example} - показать дни кождения в конференции.\",",
"слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни",
"else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день",
"+ bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in sorted(data, key=lambda x: x[1]))",
"example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей в группе",
"await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в беседе ✨:\\n\" data =",
"plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in = bdate_in[:-1] + \",",
"\" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message +=",
"offset == 0: return await msg.answer(\"Не удалось получить сообщество или оно пусто!\") break",
"многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни рождения",
"break message = f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not",
"= check_date.replace(year=now.year + 1) difference = check_date - now bdate_in = \" (будет",
"for m in members: if \"bdate\" not in m or \"deactivated\" in m:",
"[f\"Дни рождения\", f\"Вывод дней рождений людей в группе или в беседе.\", f\"{example} -",
"datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date =",
"or \"items\" not in result or not result[\"items\"]: if offset == 0: return",
"if argument: members = [] offset = 0 while True: result = await",
"argument: members = [] offset = 0 while True: result = await msg.api.groups.getMembers(group_id=argument,",
"message = f\"Дни рождения пользователей в беседе ✨:\\n\" data = [] now =",
"или оно пусто!\") break members += result[\"items\"] offset += 1000 if result[\"count\"] >",
"= (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example",
"пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id,",
"рождения пользователей в беседе ✨:\\n\" data = [] now = datetime.datetime.today().date() for m",
"\"дня\", \"дней\")) + \")\" if year: bdate_in = bdate_in[:-1] + \", исполнится \"",
"offset = 0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not",
"m in members: if \"bdate\" not in m or \"deactivated\" in m: continue",
"- now bdate_in = \" (будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\"))",
"difference.days)) message += \"\\n\".join(d[0] for d in sorted(data, key=lambda x: x[1])) return await",
"msg.answer(\"Не удалось получить сообщество или оно пусто!\") break members += result[\"items\"] offset +=",
"datetime.date(user_date.year, 1, 1)) difference = check_date - now if difference.days < 0: check_date",
"data = [] now = datetime.datetime.today().date() for m in members: if \"bdate\" not",
"дней рождений людей в группе или в беседе.\", f\"{example} - показать дни кождения",
"def process_message(self, msg): command, argument = self.parse_message(msg) if argument: members = [] offset",
"рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example = self.command_example()",
"< 0: check_date = check_date.replace(year=now.year + 1) difference = check_date - now bdate_in",
"user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1,",
"if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\"",
"+ plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in = bdate_in[:-1] +",
"> self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут показана",
"super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description",
"в беседе ✨:\\n\" data = [] now = datetime.datetime.today().date() for m in members:",
"break members += result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы",
"людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни рождения пользователей",
"рождения пользователей в группу.\"] async def process_message(self, msg): command, argument = self.parse_message(msg) if",
"True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\" not",
"else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в беседе",
"\")\" if year: bdate_in = bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) +",
"datetime from handler.base_plugin import CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__",
"f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни рождения пользователей в",
"user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in sorted(data, key=lambda x:",
"commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self):",
"in group (but no more than `max_users_in_group`), for users in conference.\"\"\" if not",
"result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\" not in",
"рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group} из пользователей\") break message =",
"= False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year)",
"difference.days < 0: check_date = check_date.replace(year=now.year + 1) difference = check_date - now",
"await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут показана лишь {self.max_users_in_group}",
"пользователей в группу.\"] async def process_message(self, msg): command, argument = self.parse_message(msg) if argument:",
"result or not result[\"items\"]: if offset == 0: return await msg.answer(\"Не удалось получить",
"m[\"first_name\"] + \" \" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in,",
"year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date =",
"группы> - показать дни рождения пользователей в группу.\"] async def process_message(self, msg): command,",
"if not result or \"items\" not in result or not result[\"items\"]: if offset",
"not in result or not result[\"items\"]: if offset == 0: return await msg.answer(\"Не",
"than `max_users_in_group`), for users in conference.\"\"\" if not commands: commands = (\"дни рождения\",)",
"день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения",
"more than `max_users_in_group`), for users in conference.\"\"\" if not commands: commands = (\"дни",
"if difference.days < 0: check_date = check_date.replace(year=now.year + 1) difference = check_date -",
"check_date - now bdate_in = \" (будет через \" + plural_form(difference.days, (\"день\", \"дня\",",
"bdate_in = \" (будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\"",
"m: continue try: if m['bdate'].count(\".\") > 1: year = True user_date = datetime.datetime.strptime(m['bdate'],",
"check_date = user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference =",
"\\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message =",
"message += \"\\n\".join(d[0] for d in sorted(data, key=lambda x: x[1])) return await msg.answer(message)",
"command, argument = self.parse_message(msg) if argument: members = [] offset = 0 while",
"max_users_in_group=1000): \"\"\"Answers with birthday for users in group (but no more than `max_users_in_group`),",
"argument = self.parse_message(msg) if argument: members = [] offset = 0 while True:",
"(\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"] + \" \"",
"\" + m[\"first_name\"] + \" \" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\")",
"= max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод",
"\" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for d in sorted(data,",
"in members: if \"bdate\" not in m or \"deactivated\" in m: continue try:",
"utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands,",
"ValueError: check_date = user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference",
"for users in conference.\"\"\" if not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes,",
"self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей в группе или в",
"continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date + (datetime.date(now.year, 1,",
"try: if m['bdate'].count(\".\") > 1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else:",
"+ plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \" +",
"✨:\\n\" else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш",
"0: return await msg.answer(\"Не удалось получить сообщество или оно пусто!\") break members +=",
"result or \"items\" not in result or not result[\"items\"]: if offset == 0:",
"offset=offset, fields=\"bdate\") if not result or \"items\" not in result or not result[\"items\"]:",
"исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍",
"рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей",
"def set_description(self): example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей",
"in result or not result[\"items\"]: if offset == 0: return await msg.answer(\"Не удалось",
"difference = check_date - now bdate_in = \" (будет через \" + plural_form(difference.days,",
"= await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else: members =",
"(datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference = check_date - now if",
"result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения слишком многих людей!\\n\" f\"Будут",
"1, 1)) difference = check_date - now if difference.days < 0: check_date =",
"\" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \"",
"datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue",
"set_description(self): example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней рождений людей в",
"user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError:",
"class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers",
"await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\" not in result or",
"беседе.\", f\"{example} - показать дни кождения в конференции.\", f\"{example} <id группы> - показать",
"msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в беседе ✨:\\n\" data = []",
"рождения\", f\"Вывод дней рождений людей в группе или в беседе.\", f\"{example} - показать",
"показать дни рождения пользователей в группу.\"] async def process_message(self, msg): command, argument =",
"msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else:",
"members += result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь",
"datetime.datetime.today().date() for m in members: if \"bdate\" not in m or \"deactivated\" in",
"user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date() except",
"через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in =",
"= await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if not result or \"items\" not in result",
"1) difference = check_date - now bdate_in = \" (будет через \" +",
"= [] offset = 0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\")",
"= datetime.datetime.strptime(m['bdate'], '%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date",
"True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'], '%d.%m').date()",
"<id группы> - показать дни рождения пользователей в группу.\"] async def process_message(self, msg):",
"сообщество или оно пусто!\") break members += result[\"items\"] offset += 1000 if result[\"count\"]",
"fields=\"bdate\") message = f\"Ваш день рождения ✨:\\n\" else: members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\")",
"дни кождения в конференции.\", f\"{example} <id группы> - показать дни рождения пользователей в",
"(\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description() def set_description(self): example =",
"\"года\", \"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"] + \" \" +",
"check_date - now if difference.days < 0: check_date = check_date.replace(year=now.year + 1) difference",
"offset += 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать дни рождения",
"f\"{example} <id группы> - показать дни рождения пользователей в группу.\"] async def process_message(self,",
"__slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday",
"(\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users",
"1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date",
"members: if \"bdate\" not in m or \"deactivated\" in m: continue try: if",
"\"items\" not in result or not result[\"items\"]: if offset == 0: return await",
"+ \" \" + m[\"last_name\"] + \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days))",
"из пользователей\") break message = f\"Дни рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else:",
"или в беседе.\", f\"{example} - показать дни кождения в конференции.\", f\"{example} <id группы>",
"+ (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference = check_date - now",
"members = await msg.api.messages.getChatUsers(chat_id=msg.chat_id, fields=\"bdate\") message = f\"Дни рождения пользователей в беседе ✨:\\n\"",
"- now if difference.days < 0: check_date = check_date.replace(year=now.year + 1) difference =",
"= check_date - now bdate_in = \" (будет через \" + plural_form(difference.days, (\"день\",",
"if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message = f\"Ваш день рождения",
"0: check_date = check_date.replace(year=now.year + 1) difference = check_date - now bdate_in =",
"max_users_in_group self.set_description() def set_description(self): example = self.command_example() self.description = [f\"Дни рождения\", f\"Вывод дней",
"[] offset = 0 while True: result = await msg.api.groups.getMembers(group_id=argument, offset=offset, fields=\"bdate\") if",
"process_message(self, msg): command, argument = self.parse_message(msg) if argument: members = [] offset =",
"= bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\", \"лет\"))",
"(\"день\", \"дня\", \"дней\")) + \")\" if year: bdate_in = bdate_in[:-1] + \", исполнится",
"= datetime.datetime.today().date() for m in members: if \"bdate\" not in m or \"deactivated\"",
"\")\" data.append((\" 🌍 \" + m[\"first_name\"] + \" \" + m[\"last_name\"] + \":",
"if m['bdate'].count(\".\") > 1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year",
"or \"deactivated\" in m: continue try: if m['bdate'].count(\".\") > 1: year = True",
"рождения пользователей в группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members = await",
"from handler.base_plugin import CommandPlugin from utils import plural_form, age class BirthdayPlugin(CommandPlugin): __slots__ =",
"in conference.\"\"\" if not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group",
"+ \")\" data.append((\" 🌍 \" + m[\"first_name\"] + \" \" + m[\"last_name\"] +",
"1, 1) - datetime.date(user_date.year, 1, 1)) difference = check_date - now if difference.days",
"= check_date - now if difference.days < 0: check_date = check_date.replace(year=now.year + 1)",
"not commands: commands = (\"дни рождения\",) super().__init__(*commands, prefixes=prefixes, strict=strict) self.max_users_in_group = max_users_in_group self.set_description()",
"now = datetime.datetime.today().date() for m in members: if \"bdate\" not in m or",
"показать дни кождения в конференции.\", f\"{example} <id группы> - показать дни рождения пользователей",
"группе \\\"{argument}\\\" ✨:\\n\" else: if not msg.is_multichat: members = await msg.api.users.get(user_ids=msg.user_id, fields=\"bdate\") message",
"✨:\\n\" data = [] now = datetime.datetime.today().date() for m in members: if \"bdate\"",
"users in group (but no more than `max_users_in_group`), for users in conference.\"\"\" if",
"= True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date() else: year = False user_date = datetime.datetime.strptime(m['bdate'],",
"+ 1, (\"год\", \"года\", \"лет\")) + \")\" data.append((\" 🌍 \" + m[\"first_name\"] +",
"лишь {self.max_users_in_group} из пользователей\") break message = f\"Дни рождения пользователей в группе \\\"{argument}\\\"",
"bdate_in = bdate_in[:-1] + \", исполнится \" + plural_form(age(user_date) + 1, (\"год\", \"года\",",
"+= result[\"items\"] offset += 1000 if result[\"count\"] > self.max_users_in_group: await msg.answer(f\"Вы пытаетесь узнать",
"в группу.\"] async def process_message(self, msg): command, argument = self.parse_message(msg) if argument: members",
"user_date + (datetime.date(now.year, 1, 1) - datetime.date(user_date.year, 1, 1)) difference = check_date -",
"in m or \"deactivated\" in m: continue try: if m['bdate'].count(\".\") > 1: year",
"continue try: if m['bdate'].count(\".\") > 1: year = True user_date = datetime.datetime.strptime(m['bdate'], '%d.%m.%Y').date()",
"\" (будет через \" + plural_form(difference.days, (\"день\", \"дня\", \"дней\")) + \")\" if year:",
"age class BirthdayPlugin(CommandPlugin): __slots__ = (\"max_users_in_group\", ) def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000):",
"= [] now = datetime.datetime.today().date() for m in members: if \"bdate\" not in",
") def __init__(self, *commands, prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in",
"'%d.%m').date() except ValueError: continue try: check_date = user_date.replace(year=now.year) except ValueError: check_date = user_date",
"[] now = datetime.datetime.today().date() for m in members: if \"bdate\" not in m",
"prefixes=None, strict=False, max_users_in_group=1000): \"\"\"Answers with birthday for users in group (but no more",
"+ \": \" + user_date.strftime(\"%d.%m\") + bdate_in, difference.days)) message += \"\\n\".join(d[0] for d"
] |
[
"Changes may cause incorrect behavior and will be lost if the code is",
"lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum",
"\"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\"",
"= \"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning =",
"Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect",
"License. See License.txt in the project root for # license information. # #",
"information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes",
"succeeded = \"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning",
"cause incorrect behavior and will be lost if the code is # regenerated.",
"= \"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating =",
"= \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing =",
"suspended = \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing",
"# Licensed under the MIT License. See License.txt in the project root for",
"deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended",
"scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed",
"= \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting =",
"ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused =",
"if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class",
"import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting =",
"= \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending =",
"code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum):",
"will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum",
"\"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\"",
"reserved. # Licensed under the MIT License. See License.txt in the project root",
"# license information. # # Code generated by Microsoft (R) AutoRest Code Generator.",
"State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused =",
"See License.txt in the project root for # license information. # # Code",
"regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\"",
"\"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\"",
"\"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\"",
"SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded =",
"AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost",
"\"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\"",
"pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed",
"\"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\"",
"(R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be",
"\"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\"",
"License.txt in the project root for # license information. # # Code generated",
"Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\"",
"be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import",
"preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded",
"by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and",
"paused = \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending",
"= \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling =",
"Generator. # Changes may cause incorrect behavior and will be lost if the",
"incorrect behavior and will be lost if the code is # regenerated. #",
"the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuTier(str,",
"= \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed =",
"\"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\"",
"enum import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting",
"Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in",
"\"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\"",
"# -------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class",
"coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"failed = \"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating",
"may cause incorrect behavior and will be lost if the code is #",
"rights reserved. # Licensed under the MIT License. See License.txt in the project",
"resuming = \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting",
"behavior and will be lost if the code is # regenerated. # --------------------------------------------------------------------------",
"Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\"",
"# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause",
"suspending = \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling",
"= \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded =",
"= \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str,",
"the project root for # license information. # # Code generated by Microsoft",
"root for # license information. # # Code generated by Microsoft (R) AutoRest",
"= \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming =",
"All rights reserved. # Licensed under the MIT License. See License.txt in the",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt",
"-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the",
"Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused = \"Paused\"",
"\"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\"",
"Licensed under the MIT License. See License.txt in the project root for #",
"\"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended = \"Suspended\"",
"for # license information. # # Code generated by Microsoft (R) AutoRest Code",
"Code Generator. # Changes may cause incorrect behavior and will be lost if",
"project root for # license information. # # Code generated by Microsoft (R)",
"class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused",
"and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from",
"generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior",
"license information. # # Code generated by Microsoft (R) AutoRest Code Generator. #",
"updating = \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming = \"Resuming\" preparing",
"\"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class ProvisioningState(str, Enum):",
"class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum): deleting = \"Deleting\" succeeded",
"# regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum): pbie_azure =",
"from enum import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str, Enum):",
"under the MIT License. See License.txt in the project root for # license",
"pausing = \"Pausing\" resuming = \"Resuming\" preparing = \"Preparing\" scaling = \"Scaling\" class",
"the MIT License. See License.txt in the project root for # license information.",
"class State(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused",
"provisioning = \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing = \"Pausing\" resuming",
"= \"Scaling\" class ProvisioningState(str, Enum): deleting = \"Deleting\" succeeded = \"Succeeded\" failed =",
"Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will",
"MIT License. See License.txt in the project root for # license information. #",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.",
"= \"Deleting\" succeeded = \"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended =",
"in the project root for # license information. # # Code generated by",
"# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #",
"= \"Suspended\" provisioning = \"Provisioning\" updating = \"Updating\" suspending = \"Suspending\" pausing =",
"# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"# # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may",
"\"Succeeded\" failed = \"Failed\" paused = \"Paused\" suspended = \"Suspended\" provisioning = \"Provisioning\"",
"-------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum): pbie_azure = \"PBIE_Azure\" class State(str,",
"is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuTier(str, Enum): pbie_azure",
"# Changes may cause incorrect behavior and will be lost if the code"
] |
[
"'git diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits =",
"= line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line): lnum = lnum +",
"subprocess lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color ' + sys.argv[1], shell=True,",
"line): lnum = lnum + 1 print(('%' + digits + 'i %s') %",
"str(len(str(len(lines)))) lnum = -1 for line in lines: line = line.rstrip('\\r\\n') if lnum",
"+ digits + 'i %s') % (lnum, line)) else: print(line) m = re.match(r'^@@",
"lnum = lnum + 1 print(('%' + digits + 'i %s') % (lnum,",
"1 print(('%' + digits + 'i %s') % (lnum, line)) else: print(line) m",
"-*- # opengitdiff.py import sys, re, subprocess lines = subprocess\\ .Popen( 'git diff",
"subprocess\\ .Popen( 'git diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines()",
"+ 1 print(('%' + digits + 'i %s') % (lnum, line)) else: print(line)",
"UTF-8 -*- # opengitdiff.py import sys, re, subprocess lines = subprocess\\ .Popen( 'git",
"if re.match(r'^[^-]', line): lnum = lnum + 1 print(('%' + digits + 'i",
"print(('%' + digits + 'i %s') % (lnum, line)) else: print(line) m =",
".stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1 for line in lines: line",
"= re.match(r'^@@ [-+0-9, ]+ @@$', line) if m: lnum = 0 print() print()",
"line = line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line): lnum = lnum",
"for line in lines: line = line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]',",
"% (lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if",
"digits + 'i %s') % (lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9,",
"%s') % (lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line)",
"+ sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1 for",
".Popen( 'git diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits",
"diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines))))",
"-*- coding: UTF-8 -*- # opengitdiff.py import sys, re, subprocess lines = subprocess\\",
"if lnum > -1: if re.match(r'^[^-]', line): lnum = lnum + 1 print(('%'",
"-1: if re.match(r'^[^-]', line): lnum = lnum + 1 print(('%' + digits +",
"opengitdiff.py import sys, re, subprocess lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color",
"# opengitdiff.py import sys, re, subprocess lines = subprocess\\ .Popen( 'git diff -U9999999",
"coding: UTF-8 -*- # opengitdiff.py import sys, re, subprocess lines = subprocess\\ .Popen(",
".readlines() digits = str(len(str(len(lines)))) lnum = -1 for line in lines: line =",
"lnum = -1 for line in lines: line = line.rstrip('\\r\\n') if lnum >",
"(lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if m:",
"line in lines: line = line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line):",
"digits = str(len(str(len(lines)))) lnum = -1 for line in lines: line = line.rstrip('\\r\\n')",
"shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1 for line in",
"in lines: line = line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line): lnum",
"--no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum =",
"re.match(r'^[^-]', line): lnum = lnum + 1 print(('%' + digits + 'i %s')",
"line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if m: lnum",
"lnum > -1: if re.match(r'^[^-]', line): lnum = lnum + 1 print(('%' +",
"= -1 for line in lines: line = line.rstrip('\\r\\n') if lnum > -1:",
"print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if m: lnum = 0",
"import sys, re, subprocess lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color '",
"= subprocess\\ .Popen( 'git diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\",
"lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\",
"' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1",
"-U9999999 --no-color ' + sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum",
"line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line): lnum = lnum + 1",
"m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if m: lnum = 0 print()",
"-1 for line in lines: line = line.rstrip('\\r\\n') if lnum > -1: if",
"<gh_stars>1-10 # -*- coding: UTF-8 -*- # opengitdiff.py import sys, re, subprocess lines",
"= lnum + 1 print(('%' + digits + 'i %s') % (lnum, line))",
"sys.argv[1], shell=True, stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1 for line",
"> -1: if re.match(r'^[^-]', line): lnum = lnum + 1 print(('%' + digits",
"'i %s') % (lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$',",
"else: print(line) m = re.match(r'^@@ [-+0-9, ]+ @@$', line) if m: lnum =",
"+ 'i %s') % (lnum, line)) else: print(line) m = re.match(r'^@@ [-+0-9, ]+",
"re, subprocess lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color ' + sys.argv[1],",
"lnum + 1 print(('%' + digits + 'i %s') % (lnum, line)) else:",
"= str(len(str(len(lines)))) lnum = -1 for line in lines: line = line.rstrip('\\r\\n') if",
"# -*- coding: UTF-8 -*- # opengitdiff.py import sys, re, subprocess lines =",
"stdout=subprocess.PIPE)\\ .stdout\\ .readlines() digits = str(len(str(len(lines)))) lnum = -1 for line in lines:",
"sys, re, subprocess lines = subprocess\\ .Popen( 'git diff -U9999999 --no-color ' +",
"lines: line = line.rstrip('\\r\\n') if lnum > -1: if re.match(r'^[^-]', line): lnum ="
] |
[
"= \"whois\" + \" \" + url process = os.popen(command) results = str(process.read())",
"import os def get_whois(url): command = \"whois\" + \" \" + url process",
"\" \" + url process = os.popen(command) results = str(process.read()) #print results return",
"\" + url process = os.popen(command) results = str(process.read()) #print results return results",
"os def get_whois(url): command = \"whois\" + \" \" + url process =",
"get_whois(url): command = \"whois\" + \" \" + url process = os.popen(command) results",
"\"whois\" + \" \" + url process = os.popen(command) results = str(process.read()) #print",
"<reponame>ntnshrm87/4hathacker<filename>web_scanner/whois.py #!/usr/bin/python import os def get_whois(url): command = \"whois\" + \" \" +",
"+ \" \" + url process = os.popen(command) results = str(process.read()) #print results",
"#!/usr/bin/python import os def get_whois(url): command = \"whois\" + \" \" + url",
"def get_whois(url): command = \"whois\" + \" \" + url process = os.popen(command)",
"command = \"whois\" + \" \" + url process = os.popen(command) results ="
] |
[
":: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System",
"\"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\",",
"open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books",
"author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads and Google",
"fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes",
"classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT",
"Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating",
"long_description=\"Scrapes books and articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(),",
"long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books",
"url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved",
"with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language ::",
"System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\",",
":: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\",",
":: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS",
"\"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts': [ 'bscrape=books_scraper.scraper:main', ],",
"and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\",",
"3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\",",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI",
"description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads and Google Scholar\",",
"setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\",",
"data scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\",",
"books and articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[",
"\"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts': [ 'bscrape=books_scraper.scraper:main', ], }, )",
"License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\",",
"= fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and",
"], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={",
"\"r\") as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data",
"scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\",",
":: MIT License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\",",
"Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\", \"License",
"Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\",",
"\"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts': [ 'bscrape=books_scraper.scraper:main',",
"\"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ],",
"OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\",",
"Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ],",
"install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts': [",
"python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts':",
"and articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming",
"as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\",",
"import setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\",",
"setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio",
"articles informatio from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language",
"from Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python",
"Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\", \"License ::",
"MIT License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\",",
":: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires='>=3.6',",
"\"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\", ], entry_points={ 'console_scripts': [ 'bscrape=books_scraper.scraper:main', ], },",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads and",
"fh.read() setuptools.setup( name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles",
"\"Operating System :: OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\",",
"name=\"books_info-bsodhi\", version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio from",
"OS Independent\", ], python_requires='>=3.6', install_requires=[\"requests\", \"cryptography\", \"pyOpenSSL\", \"lxml\", \"argparse\", \"beautifulsoup4\", \"fake_useragent\", \"scholarly\", \"selenium\",",
"packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved ::",
"Goodreads and Google Scholar\", long_description_content_type=\"text/markdown\", url=\"https://github.com/bsodhi/books_scraper\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python ::",
"Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System ::",
"version=\"0.0.2\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"Books data scraper.\", long_description=\"Scrapes books and articles informatio from Goodreads"
] |
[
"> c: return a, c else: return a, b def eh_triangulo(a, b, c):",
"b and b == c: return True return False def eh_isosceles(a, b, c):",
"elif b > a and b > c: return b else: return c",
"if a > b and a > c: return a elif b >",
"c): if a > b and a > c: return b, c elif",
"if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b, c): return 2 elif",
"a elif b > a and b > c: return b else: return",
"a > c: return b, c elif b > a and b >",
"if (lado_a < 1) or (lado_b < 1) or (lado_c < 1): print(\"Valor",
"b, c): if (a == b) or (a == c) or (b ==",
"eh_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a, b,",
"== c) or (b == c): return True return False def eh_escaleno(a, b,",
"def eh_equilatero(a, b, c): if a == b and b == c: return",
"b, c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a, b, c)",
"= lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) a, b, c",
"1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif tipo == 3:",
"print(\"Informe três valores!\") lado_a = int(input()) lado_b = int(input()) lado_c = int(input()) if",
"c: return a, c else: return a, b def eh_triangulo(a, b, c): _a",
"== True: print(\"Informe três valores!\") lado_a = int(input()) lado_b = int(input()) lado_c =",
"> a and b > c: return a, c else: return a, b",
"(lado_b < 1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores que",
"lado_b = int(input()) lado_c = int(input()) if (lado_a < 1) or (lado_b <",
"print(\"Insira valores maiores que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\")",
"<filename>triangulos.py def lado_maior(a, b, c): if a > b and a > c:",
"triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]: \") if (novo == \"N\"):",
"tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif tipo",
"(b != c): return True return False def tipo_triangulo(a, b, c): _a =",
"return c def lados_menores(a, b, c): if a > b and a >",
"True return False def eh_escaleno(a, b, c): if (a != b) and (a",
"and b > c: return b else: return c def lados_menores(a, b, c):",
"b, c = _a, _b, _c if eh_equilatero(a, b, c): return 1 elif",
"b else: return c def lados_menores(a, b, c): if a > b and",
"> b and a > c: return b, c elif b > a",
"c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) if",
"b, c) a, b, c = _a, _b, _c if eh_equilatero(a, b, c):",
"int(input()) lado_c = int(input()) if (lado_a < 1) or (lado_b < 1) or",
"triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif",
"a, b def eh_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c",
"def lado_maior(a, b, c): if a > b and a > c: return",
"c) and (b != c): return True return False def tipo_triangulo(a, b, c):",
"= int(input()) lado_c = int(input()) if (lado_a < 1) or (lado_b < 1)",
"False def tipo_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c =",
"c): if a == b and b == c: return True return False",
"return False def tipo_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c",
"return True return False def eh_escaleno(a, b, c): if (a != b) and",
"1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else : if eh_triangulo(lado_a, lado_b,",
"3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo = input(\"Deseja fazer nova",
"b) or (a == c) or (b == c): return True return False",
"print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo",
"elif tipo == 2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else:",
"b, c): if (a != b) and (a != c) and (b !=",
"c): return True return False def tipo_triangulo(a, b, c): _a = lado_maior(a, b,",
"b > a and b > c: return b else: return c def",
"int(input()) if (lado_a < 1) or (lado_b < 1) or (lado_c < 1):",
"b, c) if _a >= _b + _c: return False else: return True",
"False else: return True def eh_equilatero(a, b, c): if a == b and",
"c) or (b == c): return True return False def eh_escaleno(a, b, c):",
"tipo_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a, b,",
"b == c: return True return False def eh_isosceles(a, b, c): if (a",
"c) a, b, c = _a, _b, _c if eh_equilatero(a, b, c): return",
"= input(\"Deseja fazer nova inserção? [S/N]: \") if (novo == \"N\"): print(\"********** fim",
"c): return 2 elif eh_escaleno(a, b, c): return 3 ler = True while",
"c: return a elif b > a and b > c: return b",
"if (a != b) and (a != c) and (b != c): return",
"!= b) and (a != c) and (b != c): return True return",
"and b == c: return True return False def eh_isosceles(a, b, c): if",
"True return False def eh_isosceles(a, b, c): if (a == b) or (a",
"elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo =",
"False def eh_isosceles(a, b, c): if (a == b) or (a == c)",
"!= c): return True return False def tipo_triangulo(a, b, c): _a = lado_maior(a,",
"1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else",
"else: return c def lados_menores(a, b, c): if a > b and a",
"errado!\") print(\"Insira valores maiores que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É",
">= _b + _c: return False else: return True def eh_equilatero(a, b, c):",
"print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\")",
"Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\")",
"else: print(\"Não é um triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]: \")",
"c else: return a, b def eh_triangulo(a, b, c): _a = lado_maior(a, b,",
"(a != b) and (a != c) and (b != c): return True",
"a and b > c: return b else: return c def lados_menores(a, b,",
"b and a > c: return a elif b > a and b",
"b, c): if a > b and a > c: return b, c",
"c): return 1 elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b, c):",
"lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1:",
"c: return b, c elif b > a and b > c: return",
"= int(input()) lado_b = int(input()) lado_c = int(input()) if (lado_a < 1) or",
"a > b and a > c: return a elif b > a",
"(a == c) or (b == c): return True return False def eh_escaleno(a,",
"tipo == 2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não",
"if _a >= _b + _c: return False else: return True def eh_equilatero(a,",
"lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) a, b, c =",
"novo = input(\"Deseja fazer nova inserção? [S/N]: \") if (novo == \"N\"): print(\"**********",
"(lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else : if",
"lados_menores(a, b, c): if a > b and a > c: return b,",
"or (b == c): return True return False def eh_escaleno(a, b, c): if",
"2 elif eh_escaleno(a, b, c): return 3 ler = True while ler ==",
"c: return True return False def eh_isosceles(a, b, c): if (a == b)",
"a, b, c = _a, _b, _c if eh_equilatero(a, b, c): return 1",
"a > c: return a elif b > a and b > c:",
"b > a and b > c: return a, c else: return a,",
"return 1 elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b, c): return",
"== 3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo = input(\"Deseja fazer",
"and a > c: return a elif b > a and b >",
"_b, _c if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b, c): return",
"b) and (a != c) and (b != c): return True return False",
"= tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif tipo ==",
"True return False def tipo_triangulo(a, b, c): _a = lado_maior(a, b, c) _b,",
"return False def eh_isosceles(a, b, c): if (a == b) or (a ==",
"== 1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif tipo ==",
"c) _b, _c = lados_menores(a, b, c) if _a >= _b + _c:",
"_c = lados_menores(a, b, c) a, b, c = _a, _b, _c if",
"return False else: return True def eh_equilatero(a, b, c): if a == b",
"= lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) if _a >=",
"return b, c elif b > a and b > c: return a,",
"b, c): return 2 elif eh_escaleno(a, b, c): return 3 ler = True",
"return 3 ler = True while ler == True: print(\"Informe três valores!\") lado_a",
"a, c else: return a, b def eh_triangulo(a, b, c): _a = lado_maior(a,",
"c): return 3 ler = True while ler == True: print(\"Informe três valores!\")",
"and (b != c): return True return False def tipo_triangulo(a, b, c): _a",
"Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo",
"and a > c: return b, c elif b > a and b",
"return True return False def tipo_triangulo(a, b, c): _a = lado_maior(a, b, c)",
"+ _c: return False else: return True def eh_equilatero(a, b, c): if a",
"if a > b and a > c: return b, c elif b",
"if (a == b) or (a == c) or (b == c): return",
"or (a == c) or (b == c): return True return False def",
"def eh_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a,",
"b, c) _b, _c = lados_menores(a, b, c) a, b, c = _a,",
"> a and b > c: return b else: return c def lados_menores(a,",
"def tipo_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a,",
"_a = lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) if _a",
"and b > c: return a, c else: return a, b def eh_triangulo(a,",
"def lados_menores(a, b, c): if a > b and a > c: return",
"return a, b def eh_triangulo(a, b, c): _a = lado_maior(a, b, c) _b,",
"if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo",
"fazer nova inserção? [S/N]: \") if (novo == \"N\"): print(\"********** fim ************\") ler",
"int(input()) lado_b = int(input()) lado_c = int(input()) if (lado_a < 1) or (lado_b",
"> c: return b else: return c def lados_menores(a, b, c): if a",
"c): if a > b and a > c: return a elif b",
"b and a > c: return b, c elif b > a and",
"== c: return True return False def eh_isosceles(a, b, c): if (a ==",
"_a, _b, _c if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b, c):",
"1) or (lado_b < 1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores",
"_c: return False else: return True def eh_equilatero(a, b, c): if a ==",
"1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b,",
"== c): return True return False def eh_escaleno(a, b, c): if (a !=",
": if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if",
"def eh_isosceles(a, b, c): if (a == b) or (a == c) or",
"else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c)",
"c: return b else: return c def lados_menores(a, b, c): if a >",
"c) _b, _c = lados_menores(a, b, c) a, b, c = _a, _b,",
"print(\"Não é um triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]: \") if",
"print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\")",
"eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo ==",
"lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\")",
"else: return True def eh_equilatero(a, b, c): if a == b and b",
"b, c): if a == b and b == c: return True return",
"c) if _a >= _b + _c: return False else: return True def",
"lados_menores(a, b, c) a, b, c = _a, _b, _c if eh_equilatero(a, b,",
"lado_maior(a, b, c): if a > b and a > c: return a",
"c elif b > a and b > c: return a, c else:",
"and (a != c) and (b != c): return True return False def",
"_c if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b, c): return 2",
"valores maiores que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo",
"a and b > c: return a, c else: return a, b def",
"or (lado_b < 1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores",
"(a != c) and (b != c): return True return False def tipo_triangulo(a,",
"c): if (a != b) and (a != c) and (b != c):",
"c): _a = lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) a,",
"!= c) and (b != c): return True return False def tipo_triangulo(a, b,",
"lados_menores(a, b, c) if _a >= _b + _c: return False else: return",
"lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo",
"< 1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else : if eh_triangulo(lado_a,",
"b > c: return a, c else: return a, b def eh_triangulo(a, b,",
"eh_isosceles(a, b, c): if (a == b) or (a == c) or (b",
"eh_escaleno(a, b, c): if (a != b) and (a != c) and (b",
"b > c: return b else: return c def lados_menores(a, b, c): if",
"_a >= _b + _c: return False else: return True def eh_equilatero(a, b,",
"ler == True: print(\"Informe três valores!\") lado_a = int(input()) lado_b = int(input()) lado_c",
"elif b > a and b > c: return a, c else: return",
"nova inserção? [S/N]: \") if (novo == \"N\"): print(\"********** fim ************\") ler =",
"c): return True return False def eh_escaleno(a, b, c): if (a != b)",
"_a = lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) a, b,",
"print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c):",
"_b, _c = lados_menores(a, b, c) a, b, c = _a, _b, _c",
"3 ler = True while ler == True: print(\"Informe três valores!\") lado_a =",
"um triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]: \") if (novo ==",
"False def eh_escaleno(a, b, c): if (a != b) and (a != c)",
"a > b and a > c: return b, c elif b >",
"= _a, _b, _c if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b,",
"b, c): return 3 ler = True while ler == True: print(\"Informe três",
"b, c elif b > a and b > c: return a, c",
"or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\") else :",
"que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo = tipo_triangulo(lado_a,",
"True while ler == True: print(\"Informe três valores!\") lado_a = int(input()) lado_b =",
"lado_c = int(input()) if (lado_a < 1) or (lado_b < 1) or (lado_c",
"lado_maior(a, b, c) _b, _c = lados_menores(a, b, c) if _a >= _b",
"> b and a > c: return a elif b > a and",
"else: return a, b def eh_triangulo(a, b, c): _a = lado_maior(a, b, c)",
"(lado_a < 1) or (lado_b < 1) or (lado_c < 1): print(\"Valor errado!\")",
"if a == b and b == c: return True return False def",
"lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo",
"a == b and b == c: return True return False def eh_isosceles(a,",
"valores!\") lado_a = int(input()) lado_b = int(input()) lado_c = int(input()) if (lado_a <",
"return b else: return c def lados_menores(a, b, c): if a > b",
"elif eh_escaleno(a, b, c): return 3 ler = True while ler == True:",
"b, c): if a > b and a > c: return a elif",
"eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b, c): return 3 ler =",
"= lados_menores(a, b, c) a, b, c = _a, _b, _c if eh_equilatero(a,",
"if tipo == 1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif",
"print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo = input(\"Deseja fazer nova inserção?",
"> c: return b, c elif b > a and b > c:",
"lado_a = int(input()) lado_b = int(input()) lado_c = int(input()) if (lado_a < 1)",
"return True return False def eh_isosceles(a, b, c): if (a == b) or",
"< 1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira valores maiores que 1!\")",
"return False def eh_escaleno(a, b, c): if (a != b) and (a !=",
"maiores que 1!\") else : if eh_triangulo(lado_a, lado_b, lado_c): print(\"É triangulo\") tipo =",
"b def eh_triangulo(a, b, c): _a = lado_maior(a, b, c) _b, _c =",
"== b) or (a == c) or (b == c): return True return",
"ler = True while ler == True: print(\"Informe três valores!\") lado_a = int(input())",
"== b and b == c: return True return False def eh_isosceles(a, b,",
"tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é um triangulo\") novo = input(\"Deseja",
"_b, _c = lados_menores(a, b, c) if _a >= _b + _c: return",
"(b == c): return True return False def eh_escaleno(a, b, c): if (a",
"c def lados_menores(a, b, c): if a > b and a > c:",
"eh_equilatero(a, b, c): if a == b and b == c: return True",
"eh_escaleno(a, b, c): return 3 ler = True while ler == True: print(\"Informe",
"eh_equilatero(a, b, c): return 1 elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a,",
"def eh_escaleno(a, b, c): if (a != b) and (a != c) and",
"> c: return a elif b > a and b > c: return",
"inserção? [S/N]: \") if (novo == \"N\"): print(\"********** fim ************\") ler = False",
"True def eh_equilatero(a, b, c): if a == b and b == c:",
"== 2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é",
"return a elif b > a and b > c: return b else:",
"elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b, c): return 3 ler",
"= int(input()) if (lado_a < 1) or (lado_b < 1) or (lado_c <",
"tipo == 1: print(\"Tipo Equilátero\") elif tipo == 2: print(\"Tipo Isósceles\") elif tipo",
"2: print(\"Tipo Isósceles\") elif tipo == 3: print(\"Tipo Escaleno\") else: print(\"Não é um",
"= lados_menores(a, b, c) if _a >= _b + _c: return False else:",
"return 2 elif eh_escaleno(a, b, c): return 3 ler = True while ler",
"= True while ler == True: print(\"Informe três valores!\") lado_a = int(input()) lado_b",
"três valores!\") lado_a = int(input()) lado_b = int(input()) lado_c = int(input()) if (lado_a",
"b, c) _b, _c = lados_menores(a, b, c) if _a >= _b +",
"_b + _c: return False else: return True def eh_equilatero(a, b, c): if",
"(a == b) or (a == c) or (b == c): return True",
"tipo_triangulo(lado_a, lado_b, lado_c) if tipo == 1: print(\"Tipo Equilátero\") elif tipo == 2:",
"input(\"Deseja fazer nova inserção? [S/N]: \") if (novo == \"N\"): print(\"********** fim ************\")",
"True: print(\"Informe três valores!\") lado_a = int(input()) lado_b = int(input()) lado_c = int(input())",
"return a, c else: return a, b def eh_triangulo(a, b, c): _a =",
"b, c): return 1 elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b,",
"return True def eh_equilatero(a, b, c): if a == b and b ==",
"while ler == True: print(\"Informe três valores!\") lado_a = int(input()) lado_b = int(input())",
"Escaleno\") else: print(\"Não é um triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]:",
"c): if (a == b) or (a == c) or (b == c):",
"1 elif eh_isosceles(a, b, c): return 2 elif eh_escaleno(a, b, c): return 3",
"é um triangulo\") novo = input(\"Deseja fazer nova inserção? [S/N]: \") if (novo",
"c = _a, _b, _c if eh_equilatero(a, b, c): return 1 elif eh_isosceles(a,",
"< 1) or (lado_b < 1) or (lado_c < 1): print(\"Valor errado!\") print(\"Insira",
"_c = lados_menores(a, b, c) if _a >= _b + _c: return False"
] |
[
"1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else:",
"+ 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\"",
"1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def",
"... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter =",
"get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute",
"ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter",
"def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) )",
"ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"]",
"0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\"",
"cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter",
"0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {} sec",
"1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def",
"seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1",
"signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep",
"time_sec): notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute",
"= 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] ==",
"notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal",
"{} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) )",
"ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and",
") ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter",
"ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {} {}",
"str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return",
") ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter",
"< times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter +",
"{} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter",
"== \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {}",
"return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec):",
"else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{}",
"signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"]))",
"if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ...",
"ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator(",
"time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal,",
"get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if",
"get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute",
"{} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter +",
"... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter =",
"and ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"],",
"import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter",
"notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"],",
"cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter",
"\"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator(",
"+ 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\"",
"= 0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter",
"times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore",
"ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] ==",
"{} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter",
"global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {}",
"{} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter +",
"= 0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\"",
"notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"],",
"time import sleep from notification import notificator from config import get_config ignore_buy_signal_counter =",
"from time import sleep from notification import notificator from config import get_config ignore_buy_signal_counter",
"ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator(",
"{} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {} sec \".format(signal[\"signal\"],",
"\"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter <",
"< times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter +",
"ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {} {}",
"time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal,",
"notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {},",
"sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {} sec",
"0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and",
"notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if",
"\"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format(",
"def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times:",
"str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return",
"\"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format(",
"if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ...",
"import time from time import sleep from notification import notificator from config import",
"ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return",
"signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"]))",
"import sleep from notification import notificator from config import get_config ignore_buy_signal_counter = 0",
"ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter",
"{}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received,",
"== \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {}",
"0 def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter <",
"notificator from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal,",
"= ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0",
"ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return",
"ignore_sell_signal_counter = 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep",
"...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {} sec \".format(signal[\"signal\"], time_sec)) return",
"+ 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0 return \"OK\"",
"<gh_stars>10-100 import time from time import sleep from notification import notificator from config",
"{}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"]",
"times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1),",
"else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter",
"received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {}",
"return \"OK\" def ignore_sell_signal_times(signal, times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter",
"sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {} sec \".format(signal[\"signal\"], time_sec))",
"return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"],",
"times): global ignore_sell_signal_counter if signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore",
"1), get_config()[\"ignore_buy_cooldown_sec\"], ) ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else:",
"times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1),",
"{} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) )",
"= ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter = 0",
"ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec)",
"def ignore_buy_signal_times(signal, times): global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times:",
"ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_sell_signal_counter =",
"\"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after",
"global ignore_buy_signal_counter if signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {}",
"\"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {} sec ...\".format(signal[\"signal\"], time_sec)",
"sleep from notification import notificator from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter",
"+ 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\"",
"\"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times): global",
"return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter = 0 return \"OK\" def ignore_sell_signal_times(signal, times):",
"seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], ) ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1",
"= 0 return \"OK\" def ingnore_signal_time(signal, time_sec): notificator( \"{} signal received, sleep {}",
"time from time import sleep from notification import notificator from config import get_config",
"\"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_buy_signal_counter + 1), get_config()[\"ignore_buy_cooldown_sec\"], )",
"from notification import notificator from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter =",
"ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"])) ignore_buy_signal_counter =",
"from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times):",
"and ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"],",
"signal[\"signal\"] == \"SELL\" and ignore_sell_signal_counter < times: notificator( \"Ignore {} {} ... cooldown",
"signal[\"signal\"] == \"BUY\" and ignore_buy_signal_counter < times: notificator( \"Ignore {} {} ... cooldown",
") ) ignore_buy_signal_counter = ignore_buy_signal_counter + 1 time.sleep(int(get_config()[\"ignore_buy_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"]))",
"notification import notificator from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0",
"\"Ignore {} {} ... cooldown {} seconds\".format( signal[\"signal\"], str(ignore_sell_signal_counter + 1), get_config()[\"ignore_sell_cooldown_sec\"], )",
"import notificator from config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def",
"config import get_config ignore_buy_signal_counter = 0 ignore_sell_signal_counter = 0 def ignore_buy_signal_times(signal, times): global",
"time_sec) ) time.sleep(time_sec) notificator(\"Execute {}, after sleep {} sec \".format(signal[\"signal\"], time_sec)) return signal",
") ) ignore_sell_signal_counter = ignore_sell_signal_counter + 1 time.sleep(int(get_config()[\"ignore_sell_cooldown_sec\"])) return \"PASS\" else: notificator(\"Execute {}\".format(signal[\"signal\"]))"
] |
[
"|___ | _ < | _| | | | |_| | | |_|",
"| | |_| | | |_| | | |___ |_| |_____| |_| \\_\\",
"|_| | | |___ |_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____|",
"color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m'",
"END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random)",
"\\ | ___| |_ _| / _ \\ / _ \\ | |",
"if \"break\" in command or \"exit\" in command: print(\"Exiting the application\") break elif",
"| _ \\ | ___| |_ _| / _ \\ / _ \\",
"| ___| |_ _| / _ \\ / _ \\ | | |",
"2: #print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt)",
"< 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the",
"import sys,os from perftool import interactive,main from os import path import sys import",
"| | |_ | | | | | | | | | |",
"| | |_) | | _| | |_) | | |_ | |",
"to exit the console\") while True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins",
"|_) | | _| | |_) | | |_ | | | |",
"\\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while True: if",
"|_____| '''+color.END inputPrompt = \">>\" if __name__ == '__main__': if len(sys.argv) < 2:",
"_____ _____ ___ ___ _ | _ \\ | ____| | _ \\",
"the console\") while True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input",
"\"break\" in command or \"exit\" in command: print(\"Exiting the application\") break elif command",
"|_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if",
"while True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input command =",
"class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE =",
"| |_ | | | | | | | | | | |",
"else: command = raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in command: print(\"Exiting",
"random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____ _____ _____ ___ ___ _",
"____ _____ _____ ___ ___ _ | _ \\ | ____| | _",
"import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m'",
"from os import path import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class",
"| |_| | | |___ |_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/",
"if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to",
"| ____| | _ \\ | ___| |_ _| / _ \\ /",
"or \"exit\" in command: print(\"Exiting the application\") break elif command == \"clear\": os.system('cls'",
"sys,os from perftool import interactive,main from os import path import sys import random",
"sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m'",
"| | |___ |_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END",
"OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE",
"| |___ | _ < | _| | | | |_| | |",
"_ \\ | ____| | _ \\ | ___| |_ _| / _",
"from perftool import interactive,main from os import path import sys import random import",
"__name__ == '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\")",
"import interactive,main from os import path import sys import random import sys sys.path.insert(0,",
"| __/ | |___ | _ < | _| | | | |_|",
"HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN",
"= input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in",
"| | |_| | | |___ |_| |_____| |_| \\_\\ |_| |_| \\___/",
"'\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____",
"path import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER =",
"class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____ _____ _____",
"| | __/ | |___ | _ < | _| | | |",
"|___ |_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt =",
"input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in command or",
"|_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__ == '__main__': if",
"Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while True: if sys.version_info[0] > 2:",
"| | | | __/ | |___ | _ < | _| |",
"LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____",
"> 2: #print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt) else: command =",
"True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt)",
"_ | _ \\ | ____| | _ \\ | ___| |_ _|",
"sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE =",
"| _| | | | |_| | | |_| | | |___ |_|",
"|_ _| / _ \\ / _ \\ | | | |_) |",
"OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END",
"= '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING =",
"\">>\" if __name__ == '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m",
"|_ | | | | | | | | | | | |",
"| | | | | | | | | | | | |",
"| _| | |_) | | |_ | | | | | |",
"| |_| | | |_| | | |___ |_| |_____| |_| \\_\\ |_|",
"print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while True:",
"command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\"",
"\\ / _ \\ | | | |_) | | _| | |_)",
"\"exit\" in command: print(\"Exiting the application\") break elif command == \"clear\": os.system('cls' if",
"break elif command == \"clear\": os.system('cls' if os.name == 'nt' else 'clear') else:",
"'\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note =",
"___| |_ _| / _ \\ / _ \\ | | | |_)",
"command == \"clear\": os.system('cls' if os.name == 'nt' else 'clear') else: interactive(command) else:",
"'\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m'",
"| | | | | | | | | | | __/ |",
"if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt) else:",
"future.builtins import input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in",
"welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____ _____ _____ ___",
"'\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING]",
"| | | | | | | | __/ | |___ | _",
"command or \"exit\" in command: print(\"Exiting the application\") break elif command == \"clear\":",
"NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED",
"| | | |_) | | _| | |_) | | |_ |",
"= '\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING =",
"| _ \\ | ____| | _ \\ | ___| |_ _| /",
"= '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN =",
"\\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__ == '__main__': if len(sys.argv)",
"== \"clear\": os.system('cls' if os.name == 'nt' else 'clear') else: interactive(command) else: main()",
"__/ | |___ | _ < | _| | | | |_| |",
"| | | | | | | | | | __/ | |___",
"#print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if",
"== '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter",
"| |_) | | _| | |_) | | |_ | | |",
"sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input command = input(welcome.inputPrompt) else: command",
"|_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\"",
"| | _| | |_) | | |_ | | | | |",
"_| | |_) | | |_ | | | | | | |",
"len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit",
"= '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +'''",
"/ _ \\ | | | |_) | | _| | |_) |",
"command: print(\"Exiting the application\") break elif command == \"clear\": os.system('cls' if os.name ==",
"the application\") break elif command == \"clear\": os.system('cls' if os.name == 'nt' else",
"___ ___ _ | _ \\ | ____| | _ \\ | ___|",
"print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while",
"import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT =",
"path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE",
"\\ | | | |_) | | _| | |_) | | |_",
"|_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__ == '__main__':",
"interactive,main from os import path import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__))))",
"_ \\ / _ \\ | | | |_) | | _| |",
"| | | | | | | __/ | |___ | _ <",
"/ _ \\ / _ \\ | | | |_) | | _|",
"color_random[0] +''' ____ _____ ____ _____ _____ ___ ___ _ | _ \\",
"| | | |_| | | |_| | | |___ |_| |_____| |_|",
"= \">>\" if __name__ == '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t",
"'''+color.END inputPrompt = \">>\" if __name__ == '__main__': if len(sys.argv) < 2: print(welcome.note)",
"console\") while True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import input command",
"'\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m'",
"'break' to exit the console\") while True: if sys.version_info[0] > 2: #print(sys.version_info) #from",
"= '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END =",
"|_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__",
"\\ | ____| | _ \\ | ___| |_ _| / _ \\",
"= '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note",
"'\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END = '\\033[0m'",
"input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in command:",
"+''' ____ _____ ____ _____ _____ ___ ___ _ | _ \\ |",
"#from future.builtins import input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\"",
"import input command = input(welcome.inputPrompt) else: command = raw_input(welcome.inputPrompt) if \"break\" in command",
"| | | | | | | | | | | | __/",
"\\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__ ==",
"note = color_random[0] +''' ____ _____ ____ _____ _____ ___ ___ _ |",
"= raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in command: print(\"Exiting the application\")",
"< | _| | | | |_| | | |_| | | |___",
"= '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____",
"= color_random[0] +''' ____ _____ ____ _____ _____ ___ ___ _ | _",
"_ \\ | | | |_) | | _| | |_) | |",
"| | | | | | __/ | |___ | _ < |",
"_| | | | |_| | | |_| | | |___ |_| |_____|",
"elif command == \"clear\": os.system('cls' if os.name == 'nt' else 'clear') else: interactive(command)",
"random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m'",
"_ \\ | ___| |_ _| / _ \\ / _ \\ |",
"| _ < | _| | | | |_| | | |_| |",
"print(\"Exiting the application\") break elif command == \"clear\": os.system('cls' if os.name == 'nt'",
"|_| | | |_| | | |___ |_| |_____| |_| \\_\\ |_| |_|",
"|_) | | |_ | | | | | | | | |",
"_____ ___ ___ _ | _ \\ | ____| | _ \\ |",
"| | | __/ | |___ | _ < | _| | |",
"2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\")",
"| |_) | | |_ | | | | | | | |",
"if __name__ == '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :-",
"command = raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in command: print(\"Exiting the",
"= '\\033[92m' WARNING = '\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE =",
"___ _ | _ \\ | ____| | _ \\ | ___| |_",
"WARNING = '\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING",
"= '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome:",
"\\033[0m :- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while True: if sys.version_info[0]",
"raw_input(welcome.inputPrompt) if \"break\" in command or \"exit\" in command: print(\"Exiting the application\") break",
"in command or \"exit\" in command: print(\"Exiting the application\") break elif command ==",
"____ _____ ____ _____ _____ ___ ___ _ | _ \\ | ____|",
"____| | _ \\ | ___| |_ _| / _ \\ / _",
"os import path import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color:",
"RED = '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class",
"perftool import interactive,main from os import path import sys import random import sys",
"<reponame>YajanaRao/Perftool import sys,os from perftool import interactive,main from os import path import sys",
"sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT",
"= '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m' RED =",
"color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____ _____ _____ ___ ___",
"_____ ____ _____ _____ ___ ___ _ | _ \\ | ____| |",
"IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING",
"in command: print(\"Exiting the application\") break elif command == \"clear\": os.system('cls' if os.name",
"'\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0] +''' ____ _____ ____ _____",
"application\") break elif command == \"clear\": os.system('cls' if os.name == 'nt' else 'clear')",
"'__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t \\t \\033[0m :- Yajana.N.Rao\") print(\"Enter 'break'",
"| | | | | __/ | |___ | _ < | _|",
"import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER = '\\033[95m' IMPORTANT = '\\33[35m' NOTICE",
"'\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m' WARNING = '\\033[93m'",
"'\\033[93m' RED = '\\033[91m' END = '\\033[0m' UNDERLINE = '\\033[4m' LOGGING = '\\33[34m'",
"exit the console\") while True: if sys.version_info[0] > 2: #print(sys.version_info) #from future.builtins import",
"| | | | | | | | | __/ | |___ |",
"print(\"Enter 'break' to exit the console\") while True: if sys.version_info[0] > 2: #print(sys.version_info)",
"\\___/ |_____| '''+color.END inputPrompt = \">>\" if __name__ == '__main__': if len(sys.argv) <",
"_| / _ \\ / _ \\ | | | |_) | |",
"UNDERLINE = '\\033[4m' LOGGING = '\\33[34m' class welcome: color_random=[color.HEADER,color.IMPORTANT,color.NOTICE,color.OKBLUE,color.OKGREEN,color.WARNING,color.RED,color.END,color.UNDERLINE,color.LOGGING] random.shuffle(color_random) note = color_random[0]",
"'\\033[95m' IMPORTANT = '\\33[35m' NOTICE = '\\033[33m' OKBLUE = '\\033[94m' OKGREEN = '\\033[92m'",
":- Yajana.N.Rao\") print(\"Enter 'break' to exit the console\") while True: if sys.version_info[0] >",
"_ < | _| | | | |_| | | |_| | |",
"| |___ |_| |_____| |_| \\_\\ |_| |_| \\___/ \\___/ |_____| '''+color.END inputPrompt",
"inputPrompt = \">>\" if __name__ == '__main__': if len(sys.argv) < 2: print(welcome.note) print(\"\\t",
"import path import sys import random import sys sys.path.insert(0, path.dirname(path.abspath(path.dirname(__file__)))) class color: HEADER"
] |
[
"if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in",
"generate a list of tiles via recursion \"\"\" from os import path as",
"{z}'): \"\"\"Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to",
"geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath))",
"json from shapely.geometry import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies",
"tiles at one higher zoom (in google tiling scheme)\"\"\" ul = (tile.google[0] *",
"feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format,",
"not a tile is completely contained in the boundary. If a tile is",
"+ 1, tile.zoom + 1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom +",
"to be formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str:",
"each tile, compute overlap with ROI boundary for qt in quad_tiles: ll, ur",
"checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether",
"100% overlap with boundary, set to `True` and algorithm can avoid calculating overlap",
"`tms` (as quad_tree is one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\"",
"in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms':",
"Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked for overlap with `roi_geom`. roi_geom:",
"json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for feat in features if feat['geometry']['type']",
"object to be formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree`",
"1), # UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)] #",
"------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that are children of `tile` and",
"qt.bounds # Get lower-left and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]),",
"read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if",
"list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td = {key: val",
"format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format. Parameters ---------- tile:",
"`google`, `tms`, or `quad_tree` format_str: str String to guide formatting. Only used for",
"be formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str",
"not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap a",
"= _get_quadrant_tiles(tile) # Compute four contained tiles # If sub-tiles are completely contained",
"be a .geojson or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as",
"for qt in quad_tiles] # For each tile, compute overlap with ROI boundary",
"format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired",
"[feat['geometry'] for feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def",
"'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False):",
"are children of `tile` and overlap the boundary \"\"\" return_tiles = [] quad_tiles",
"or `quad_tree` format_str: str String to guide formatting. Only used for `google` or",
"['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to",
"area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons.",
"_calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return",
"geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for feat in",
"ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that",
"formatting. Only used for `google` or `tms` (as quad_tree is one value). Default:",
"feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert",
"to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format:",
"+ 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def",
"Tiles that are children of `tile` and overlap the boundary \"\"\" return_tiles =",
"2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0],",
"indicies of tiles at one higher zoom (in google tiling scheme)\"\"\" ul =",
"(in google tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] * 2) return",
"Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one",
"zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return",
"------- bounds: list List of geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath):",
"found to have 100% overlap with boundary, set to `True` and algorithm can",
"with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this to",
"to avoid checking overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif",
"containing boundaries. Returns: ------- bounds: list List of geometries read from geojson file.\"\"\"",
"Compute four contained tiles # If sub-tiles are completely contained within boundary, no",
"tiles # If sub-tiles are completely contained within boundary, no need to compute",
"contained tiles # If sub-tiles are completely contained within boundary, no need to",
"features = raw_json['features'] bounds = [feat['geometry'] for feat in features if feat['geometry']['type'] in",
"[tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {}",
"that is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained:",
"and algorithm can avoid calculating overlap for all future child tiles. Default False.",
"overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area > 0:",
"pygeotile.tile.Tile, bool Tiles that are children of `tile` and overlap the boundary \"\"\"",
"to `True` and algorithm can avoid calculating overlap for all future child tiles.",
"geojson containing boundaries. Returns: ------- bounds: list List of geometries read from geojson",
"raise ValueError('{} should be a .geojson or .json file'.format(geojson_fpath)) bounds = None with",
"\"\"\" utils.py @author: developmentseed Functions used to generate a list of tiles via",
"UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)] # LR def",
"raw_json['features'] bounds = [feat['geometry'] for feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']]",
"Tile that is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest.",
"str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String to guide",
"+ 1, ul[1] + 1, tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2):",
"format_str: str String to guide formatting. Only used for `google` or `tms` (as",
"tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), #",
"If sub-tiles are completely contained within boundary, no need to compute overlap if",
"Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile",
"value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td",
"`True` and algorithm can avoid calculating overlap for all future child tiles. Default",
"val for key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td)",
"with ROI boundary for qt in quad_tiles: ll, ur = qt.bounds # Get",
"+ 1, tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\"",
"tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this",
"(ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of tile with ROI overlap_area",
"overlap with ROI boundary for qt in quad_tiles: ll, ur = qt.bounds #",
"(tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), #",
"tile, compute overlap with ROI boundary for qt in quad_tiles: ll, ur =",
"Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] + 1, ul[1]",
"str String to guide formatting. Only used for `google` or `tms` (as quad_tree",
"elif tile_format == 'tms': td = {key: val for key, val in zip(['x',",
"completely_contained=False): \"\"\"Find all children tiles that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile",
"Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td = {key: val for key,",
"a tile is completely contained in the boundary. If a tile is found",
"geojson_fpath: str Filepath of to geojson containing boundaries. Returns: ------- bounds: list List",
"= {key: val for key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])}",
"in quad_tiles: ll, ur = qt.bounds # Get lower-left and upper-right points tile_pts",
"def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons. Parameters: ---------- geojson_fpath: str",
"not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should be a .geojson or",
".geojson or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as geojson_f: raw_json",
"or not a tile is completely contained in the boundary. If a tile",
"[Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom +",
"val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format ==",
"completely_contained: return [[qt, True] for qt in quad_tiles] # For each tile, compute",
"in quad_tiles] # For each tile, compute overlap with ROI boundary for qt",
"ul[1] + 1, tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area",
"\"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles #",
"bounds: list List of geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise",
"for all future child tiles. Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile,",
"to guide formatting. Only used for `google` or `tms` (as quad_tree is one",
"val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format ==",
"else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children",
"Functions used to generate a list of tiles via recursion \"\"\" from os",
"return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles # If",
"avoid calculating overlap for all future child tiles. Default False. Returns: ------- return_tiles:",
"# LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] +",
"(as quad_tree is one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if",
"If a tile is found to have 100% overlap with boundary, set to",
"True] for qt in quad_tiles] # For each tile, compute overlap with ROI",
"100% overlap, indicate this to avoid checking overlap in future if overlap_area ==",
"tile_format == 'google': td = {key: val for key, val in zip(['x', 'y',",
"bool Tiles that are children of `tile` and overlap the boundary \"\"\" return_tiles",
"overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area > 0: return_tiles.append([qt, False]) return return_tiles",
"format. `google`, `tms`, or `quad_tree` format_str: str String to guide formatting. Only used",
"or `tms` (as quad_tree is one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\"",
"ROI boundary for qt in quad_tiles: ll, ur = qt.bounds # Get lower-left",
"qt in quad_tiles] # For each tile, compute overlap with ROI boundary for",
"[tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td = {key: val for key,",
"+ 1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] + 1, ul[1] +",
"four contained tiles # If sub-tiles are completely contained within boundary, no need",
"pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile format. `google`, `tms`,",
"in ['.geojson', '.json']: raise ValueError('{} should be a .geojson or .json file'.format(geojson_fpath)) bounds",
"of tiles via recursion \"\"\" from os import path as op import json",
"for key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif",
"tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile,",
"in the boundary. If a tile is found to have 100% overlap with",
"in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile",
"For each tile, compute overlap with ROI boundary for qt in quad_tiles: ll,",
"+ [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`:",
"tile: pygeotile.tile.Tile Tile that is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary",
"if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area > 0: return_tiles.append([qt, False]) return",
"'tms': td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.tms)",
"file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features",
"op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']:",
"op import json from shapely.geometry import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile):",
"os import path as op import json from shapely.geometry import Polygon from pygeotile.tile",
"= {key: val for key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])}",
"---------- geojson_fpath: str Filepath of to geojson containing boundaries. Returns: ------- bounds: list",
"completely_contained: bool Whether or not a tile is completely contained in the boundary.",
"quad_tiles] # For each tile, compute overlap with ROI boundary for qt in",
"this to avoid checking overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True])",
"tile_polygon) # If 100% overlap, indicate this to avoid checking overlap in future",
"\"\"\" if tile_format == 'google': td = {key: val for key, val in",
"= (tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1),",
"{} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap",
"region-of-interest. completely_contained: bool Whether or not a tile is completely contained in the",
"overlap for all future child tiles. Default False. Returns: ------- return_tiles: list of",
"Boundary of region-of-interest. completely_contained: bool Whether or not a tile is completely contained",
"== 'google': td = {key: val for key, val in zip(['x', 'y', 'z'],",
"a tile is found to have 100% overlap with boundary, set to `True`",
"1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath):",
"{y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td = {key: val",
"\"\"\"Find all children tiles that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile",
"of `tile` and overlap the boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile)",
"tile format. `google`, `tms`, or `quad_tree` format_str: str String to guide formatting. Only",
"all future child tiles. Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool",
"# UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)] # LR",
"bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format. Parameters",
"shapely.geometry import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles",
"'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td = {key:",
"Only used for `google` or `tms` (as quad_tree is one value). Default: \"{x}",
"of tiles at one higher zoom (in google tiling scheme)\"\"\" ul = (tile.google[0]",
"{key: val for key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return",
"`roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or not a tile",
"ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of tile",
"\"\"\"Return indicies of tiles at one higher zoom (in google tiling scheme)\"\"\" ul",
"from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher",
"Get lower-left and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]),",
"import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at",
"from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not",
"Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td =",
"boundaries. Returns: ------- bounds: list List of geometries read from geojson file.\"\"\" if",
"1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0]",
"Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), # LL Tile.from_google(ul[0] + 1, ul[1],",
"= Polygon(tile_pts) # Calculate overlap of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon)",
"if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should be a .geojson",
"def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap a boundary Parameters",
"list of pygeotile.tile.Tile, bool Tiles that are children of `tile` and overlap the",
"= None with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features']",
"recursion \"\"\" from os import path as op import json from shapely.geometry import",
"as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for feat",
"1, tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return",
"'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td =",
"file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not",
"'.json']: raise ValueError('{} should be a .geojson or .json file'.format(geojson_fpath)) bounds = None",
"\"\"\"Load geojson and return all contained polygons. Parameters: ---------- geojson_fpath: str Filepath of",
"of region-of-interest. completely_contained: bool Whether or not a tile is completely contained in",
"\"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td = {key: val for key, val",
"= _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this to avoid checking overlap",
"ul[1] + 1, tile.zoom + 1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom",
"`tile` and overlap the boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) #",
"open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry']",
"boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles",
"the boundary. If a tile is found to have 100% overlap with boundary,",
"have 100% overlap with boundary, set to `True` and algorithm can avoid calculating",
"FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{}",
"bounds = None with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features =",
"\"\"\"Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be",
"set to `True` and algorithm can avoid calculating overlap for all future child",
"that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked for",
"tile is completely contained in the boundary. If a tile is found to",
"['.geojson', '.json']: raise ValueError('{} should be a .geojson or .json file'.format(geojson_fpath)) bounds =",
"tiles via recursion \"\"\" from os import path as op import json from",
"Whether or not a tile is completely contained in the boundary. If a",
"are completely contained within boundary, no need to compute overlap if completely_contained: return",
"to geojson containing boundaries. Returns: ------- bounds: list List of geometries read from",
"key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format",
"upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon",
"ValueError('{} should be a .geojson or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath,",
"LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] + 1,",
"for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or",
"import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher zoom (in",
"{key: val for key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return",
"= raw_json['features'] bounds = [feat['geometry'] for feat in features if feat['geometry']['type'] in ['Polygon',",
"format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile",
"`google` or `tms` (as quad_tree is one value). Default: \"{x} {y} {z}\". Example:",
"overlap the boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute four",
"---------- tile: pygeotile.tile.Tile Tile that is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape",
"overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons. Parameters:",
"def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and",
"quad_tiles: ll, ur = qt.bounds # Get lower-left and upper-right points tile_pts =",
"return all contained polygons. Parameters: ---------- geojson_fpath: str Filepath of to geojson containing",
"td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.google) +",
"overlap, indicate this to avoid checking overlap in future if overlap_area == tile_polygon.area:",
"via recursion \"\"\" from os import path as op import json from shapely.geometry",
"necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str",
"boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked for overlap with `roi_geom`.",
"= [] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles # If sub-tiles",
"_get_quadrant_tiles(tile) # Compute four contained tiles # If sub-tiles are completely contained within",
"roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap a boundary Parameters ---------- tile:",
"polygons. Parameters: ---------- geojson_fpath: str Filepath of to geojson containing boundaries. Returns: -------",
"ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this to avoid",
"Returns: ------- bounds: list List of geometries read from geojson file.\"\"\" if not",
"of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate",
"compute overlap if completely_contained: return [[qt, True] for qt in quad_tiles] # For",
"is one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format ==",
"of geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not",
"# Compute four contained tiles # If sub-tiles are completely contained within boundary,",
"get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap a boundary Parameters ----------",
"Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that are children",
"algorithm can avoid calculating overlap for all future child tiles. Default False. Returns:",
"a list of tiles via recursion \"\"\" from os import path as op",
"or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as geojson_f: raw_json =",
"pygeotile.tile.Tile Tile that is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of",
"sub-tiles are completely contained within boundary, no need to compute overlap if completely_contained:",
"Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher zoom (in google",
"one higher zoom (in google tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1]",
"return format_str.format(**td) elif tile_format == 'tms': td = {key: val for key, val",
"overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked for overlap",
"return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons. Parameters: ----------",
"overlap of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap,",
"contained within boundary, no need to compute overlap if completely_contained: return [[qt, True]",
"guide formatting. Only used for `google` or `tms` (as quad_tree is one value).",
"zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td",
"# For each tile, compute overlap with ROI boundary for qt in quad_tiles:",
"'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree",
"that are children of `tile` and overlap the boundary \"\"\" return_tiles = []",
"tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts)",
"contained polygons. Parameters: ---------- geojson_fpath: str Filepath of to geojson containing boundaries. Returns:",
"return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom",
"should be a .geojson or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r')",
"the boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained",
"ll, ur = qt.bounds # Get lower-left and upper-right points tile_pts = ((ll[1],",
"tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all",
"= qt.bounds # Get lower-left and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1],",
"[] quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles # If sub-tiles are",
"in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area > 0: return_tiles.append([qt,",
"return_tiles: list of pygeotile.tile.Tile, bool Tiles that are children of `tile` and overlap",
"'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for",
"tile is found to have 100% overlap with boundary, set to `True` and",
"in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree':",
"{z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td = {key: val for",
"`tms`, or `quad_tree` format_str: str String to guide formatting. Only used for `google`",
"used for `google` or `tms` (as quad_tree is one value). Default: \"{x} {y}",
"`quad_tree` format_str: str String to guide formatting. Only used for `google` or `tms`",
"completely contained within boundary, no need to compute overlap if completely_contained: return [[qt,",
"ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap",
"checking overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area >",
"in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x}",
"can avoid calculating overlap for all future child tiles. Default False. Returns: -------",
".json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read())",
"# Calculate overlap of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If",
"geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all",
"pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher zoom",
"if completely_contained: return [[qt, True] for qt in quad_tiles] # For each tile,",
"{y} {z}'): \"\"\"Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object",
"future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area > 0: return_tiles.append([qt, False])",
"def _get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher zoom (in google tiling",
"def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format. Parameters ----------",
"elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def",
"Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)] # LR def _calc_overlap(geom1,",
"raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for feat in features",
"bounds = [feat['geometry'] for feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return",
"a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked for overlap with",
"completely contained in the boundary. If a tile is found to have 100%",
"shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or not a tile is completely",
"for qt in quad_tiles: ll, ur = qt.bounds # Get lower-left and upper-right",
"all contained polygons. Parameters: ---------- geojson_fpath: str Filepath of to geojson containing boundaries.",
"= json.loads(geojson_f.read()) features = raw_json['features'] bounds = [feat['geometry'] for feat in features if",
"compute overlap with ROI boundary for qt in quad_tiles: ll, ur = qt.bounds",
"future child tiles. Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles",
"does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should",
"if tile_format == 'google': td = {key: val for key, val in zip(['x',",
"path as op import json from shapely.geometry import Polygon from pygeotile.tile import Tile",
"geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath)",
"tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted.",
"format_str.format(**td) elif tile_format == 'tms': td = {key: val for key, val in",
"1, ul[1] + 1, tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return",
"overlap if completely_contained: return [[qt, True] for qt in quad_tiles] # For each",
"Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that are children of `tile`",
"Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String to guide formatting.",
"List of geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{} does",
"return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not",
"tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile",
"formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String",
"# If sub-tiles are completely contained within boundary, no need to compute overlap",
"is completely contained in the boundary. If a tile is found to have",
"+ 1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), # UR",
"contained in the boundary. If a tile is found to have 100% overlap",
"'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else:",
"LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson",
"and return all contained polygons. Parameters: ---------- geojson_fpath: str Filepath of to geojson",
"geojson and return all contained polygons. Parameters: ---------- geojson_fpath: str Filepath of to",
"from os import path as op import json from shapely.geometry import Polygon from",
"tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile format. `google`,",
"tile.zoom + 1)] # LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area",
"boundary, no need to compute overlap if completely_contained: return [[qt, True] for qt",
"at one higher zoom (in google tiling scheme)\"\"\" ul = (tile.google[0] * 2,",
"exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should be a",
"tile.zoom + 1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1), #",
"children of `tile` and overlap the boundary \"\"\" return_tiles = [] quad_tiles =",
"list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise",
"str Filepath of to geojson containing boundaries. Returns: ------- bounds: list List of",
"raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles",
"list of tiles via recursion \"\"\" from os import path as op import",
"'google': td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.google)",
"tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1],",
"2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] + 1,",
"geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons. Parameters: ---------- geojson_fpath:",
"tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1]",
"tile.zoom + 1), # UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom +",
"= [feat['geometry'] for feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds",
"to generate a list of tiles via recursion \"\"\" from os import path",
"tile_format == 'tms': td = {key: val for key, val in zip(['x', 'y',",
"to have 100% overlap with boundary, set to `True` and algorithm can avoid",
"1, tile.zoom + 1), # LL Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1),",
"not in ['.geojson', '.json']: raise ValueError('{} should be a .geojson or .json file'.format(geojson_fpath))",
"((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate",
"as op import json from shapely.geometry import Polygon from pygeotile.tile import Tile def",
"boundary. If a tile is found to have 100% overlap with boundary, set",
"ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of tile with ROI overlap_area =",
"no need to compute overlap if completely_contained: return [[qt, True] for qt in",
"avoid checking overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt, True]) elif overlap_area",
"within boundary, no need to compute overlap if completely_contained: return [[qt, True] for",
"None with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds",
"return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary format.",
"from shapely.geometry import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return indicies of",
"tile_polygon = Polygon(tile_pts) # Calculate overlap of tile with ROI overlap_area = _calc_overlap(roi_geom,",
"format_str.format(**td) elif tile_format == 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format))",
"higher zoom (in google tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] *",
"to compute overlap if completely_contained: return [[qt, True] for qt in quad_tiles] #",
"import json from shapely.geometry import Polygon from pygeotile.tile import Tile def _get_quadrant_tiles(tile): \"\"\"Return",
"with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or not a",
"ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1),",
"calculating overlap for all future child tiles. Default False. Returns: ------- return_tiles: list",
"bool Whether or not a tile is completely contained in the boundary. If",
"Calculate overlap of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100%",
"child tiles. Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that",
"recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find all children tiles that overlap a boundary",
"and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0]))",
"one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google':",
"[[qt, True] for qt in quad_tiles] # For each tile, compute overlap with",
"used to generate a list of tiles via recursion \"\"\" from os import",
"roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or not a tile is",
"not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should be",
"return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom, completely_contained=False): \"\"\"Find",
"is checked for overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool",
"overlap_area = _calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this to avoid checking",
"all children tiles that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that",
"\"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format == 'google': td = {key:",
"@author: developmentseed Functions used to generate a list of tiles via recursion \"\"\"",
"if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'):",
"Polygon(tile_pts) # Calculate overlap of tile with ROI overlap_area = _calc_overlap(roi_geom, tile_polygon) #",
"== 'tms': td = {key: val for key, val in zip(['x', 'y', 'z'],",
"\"\"\" from os import path as op import json from shapely.geometry import Polygon",
"features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y}",
"String to guide formatting. Only used for `google` or `tms` (as quad_tree is",
"import path as op import json from shapely.geometry import Polygon from pygeotile.tile import",
"and overlap the boundary \"\"\" return_tiles = [] quad_tiles = _get_quadrant_tiles(tile) # Compute",
"tiles. Default False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that are",
"(ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of tile with",
"_get_quadrant_tiles(tile): \"\"\"Return indicies of tiles at one higher zoom (in google tiling scheme)\"\"\"",
"Filepath of to geojson containing boundaries. Returns: ------- bounds: list List of geometries",
"not op.exists(geojson_fpath): raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson',",
"for feat in features if feat['geometry']['type'] in ['Polygon', 'MultiPolygon']] return bounds def format_tile(tile,",
"== 'quad_tree': return tile.quad_tree else: raise ValueError('`tile_format`: {} not recognized'.format(tile_format)) def get_overlap_child_tiles(tile, roi_geom,",
"op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise ValueError('{} should be a .geojson or .json",
"ur = qt.bounds # Get lower-left and upper-right points tile_pts = ((ll[1], ll[0]),",
"* 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL Tile.from_google(ul[0], ul[1] +",
"a .geojson or .json file'.format(geojson_fpath)) bounds = None with open(geojson_fpath, 'r') as geojson_f:",
"with boundary, set to `True` and algorithm can avoid calculating overlap for all",
"overlap with `roi_geom`. roi_geom: shapely.geometry.shape Boundary of region-of-interest. completely_contained: bool Whether or not",
"lower-left and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1],",
"val for key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td)",
"(ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of",
"quad_tree is one value). Default: \"{x} {y} {z}\". Example: \"{z}-{x}-{y}\" \"\"\" if tile_format",
"# UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), # LL Tile.from_google(ul[0] +",
"+ 1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), # LL",
"tiles that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is checked",
"boundary for qt in quad_tiles: ll, ur = qt.bounds # Get lower-left and",
"If 100% overlap, indicate this to avoid checking overlap in future if overlap_area",
"+ [tile.zoom])} return format_str.format(**td) elif tile_format == 'tms': td = {key: val for",
"return [[qt, True] for qt in quad_tiles] # For each tile, compute overlap",
"False. Returns: ------- return_tiles: list of pygeotile.tile.Tile, bool Tiles that are children of",
"points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon =",
"of pygeotile.tile.Tile, bool Tiles that are children of `tile` and overlap the boundary",
"= ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) #",
"'MultiPolygon']] return bounds def format_tile(tile, tile_format, format_str='{x} {y} {z}'): \"\"\"Convert tile to necessary",
"td = {key: val for key, val in zip(['x', 'y', 'z'], list(tile.tms) +",
"is found to have 100% overlap with boundary, set to `True` and algorithm",
"boundary, set to `True` and algorithm can avoid calculating overlap for all future",
"1, ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] + 1, ul[1] + 1,",
"# Get lower-left and upper-right points tile_pts = ((ll[1], ll[0]), (ur[1], ll[0]), (ur[1],",
"# LR def _calc_overlap(geom1, geom2): \"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load",
"developmentseed Functions used to generate a list of tiles via recursion \"\"\" from",
"tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String to",
"+ 1), # UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)]",
"_calc_overlap(roi_geom, tile_polygon) # If 100% overlap, indicate this to avoid checking overlap in",
"1), # UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), # LL Tile.from_google(ul[0]",
"indicate this to avoid checking overlap in future if overlap_area == tile_polygon.area: return_tiles.append([qt,",
"quad_tiles = _get_quadrant_tiles(tile) # Compute four contained tiles # If sub-tiles are completely",
"overlap with boundary, set to `True` and algorithm can avoid calculating overlap for",
"utils.py @author: developmentseed Functions used to generate a list of tiles via recursion",
"google tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0],",
"need to compute overlap if completely_contained: return [[qt, True] for qt in quad_tiles]",
"zoom (in google tiling scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] * 2)",
"ur[0]), (ll[1], ur[0])) tile_polygon = Polygon(tile_pts) # Calculate overlap of tile with ROI",
"raise FileNotFoundError('{} does not exist'.format(geojson_fpath)) if not op.splitext(geojson_fpath) not in ['.geojson', '.json']: raise",
"with open(geojson_fpath, 'r') as geojson_f: raw_json = json.loads(geojson_f.read()) features = raw_json['features'] bounds =",
"UL Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1), # LL Tile.from_google(ul[0] + 1,",
"qt in quad_tiles: ll, ur = qt.bounds # Get lower-left and upper-right points",
"for key, val in zip(['x', 'y', 'z'], list(tile.tms) + [tile.zoom])} return format_str.format(**td) elif",
"* 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom + 1), # UL",
"of to geojson containing boundaries. Returns: ------- bounds: list List of geometries read",
"children tiles that overlap a boundary Parameters ---------- tile: pygeotile.tile.Tile Tile that is",
"---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile format.",
"load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained polygons. Parameters: ---------- geojson_fpath: str Filepath",
"# If 100% overlap, indicate this to avoid checking overlap in future if",
"Parameters: ---------- geojson_fpath: str Filepath of to geojson containing boundaries. Returns: ------- bounds:",
"key, val in zip(['x', 'y', 'z'], list(tile.google) + [tile.zoom])} return format_str.format(**td) elif tile_format",
"\"\"\"Return area overlap\"\"\" return geom1.intersection(geom2).area def load_geojson(geojson_fpath): \"\"\"Load geojson and return all contained",
"scheme)\"\"\" ul = (tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom",
"ul = (tile.google[0] * 2, tile.google[1] * 2) return [Tile.from_google(ul[0], ul[1], tile.zoom +",
"Tile object to be formatted. tile_format: str Desired tile format. `google`, `tms`, or",
"for `google` or `tms` (as quad_tree is one value). Default: \"{x} {y} {z}\".",
"ul[1], tile.zoom + 1), # UR Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom",
"list List of geometries read from geojson file.\"\"\" if not op.exists(geojson_fpath): raise FileNotFoundError('{}"
] |