ngram
listlengths 0
67.8k
|
|---|
[
"6] for i in range(5): for k in range(i+1, 5): print(i, k) print(\"array\")",
"k) print(\"array\") n = len(ar) for i in range(n): for k in range(i,",
"n = len(ar) for i in range(n): for k in range(i, n): print(ar[i],",
"7, 2, 6] for i in range(5): for k in range(i+1, 5): print(i,",
"2, 6] for i in range(5): for k in range(i+1, 5): print(i, k)",
"print(\"array\") n = len(ar) for i in range(n): for k in range(i, n):",
"for i in range(5): for k in range(i+1, 5): print(i, k) print(\"array\") n",
"= [1, 4, 7, 2, 6] for i in range(5): for k in",
"5): print(i, k) print(\"array\") n = len(ar) for i in range(n): for k",
"[1, 4, 7, 2, 6] for i in range(5): for k in range(i+1,",
"range(5): for k in range(i+1, 5): print(i, k) print(\"array\") n = len(ar) for",
"4, 7, 2, 6] for i in range(5): for k in range(i+1, 5):",
"in range(i+1, 5): print(i, k) print(\"array\") n = len(ar) for i in range(n):",
"range(i+1, 5): print(i, k) print(\"array\") n = len(ar) for i in range(n): for",
"i in range(5): for k in range(i+1, 5): print(i, k) print(\"array\") n =",
"in range(5): for k in range(i+1, 5): print(i, k) print(\"array\") n = len(ar)",
"k in range(i+1, 5): print(i, k) print(\"array\") n = len(ar) for i in",
"= len(ar) for i in range(n): for k in range(i, n): print(ar[i], ar[k])",
"print(i, k) print(\"array\") n = len(ar) for i in range(n): for k in",
"ar = [1, 4, 7, 2, 6] for i in range(5): for k",
"for k in range(i+1, 5): print(i, k) print(\"array\") n = len(ar) for i",
"<reponame>Jagrmi-C/jagrmitest ar = [1, 4, 7, 2, 6] for i in range(5): for"
] |
[
"filename: str, level: int = 10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented",
"to support safe logging. Args: logger_name (str): name given to current logger. level",
"current logger. level (int): severity level. filename (str): file to throw all logs",
") -> logging.getLogger: \"\"\"Simple logger configuration implemented to support safe logging. Args: logger_name",
"logging. Args: logger_name (str): name given to current logger. level (int): severity level.",
"to current logger. level (int): severity level. filename (str): file to throw all",
"(int): severity level. filename (str): file to throw all logs to. Raises: LogsNotEnabled:",
"\"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level: int = 10, ) ->",
"logger in configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name)",
"level. filename (str): file to throw all logs to. Raises: LogsNotEnabled: Raised if",
"10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented to support safe logging. Args:",
"= 10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented to support safe logging.",
"with out enabling logger in configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]:",
"(str): name given to current logger. level (int): severity level. filename (str): file",
"filename (str): file to throw all logs to. Raises: LogsNotEnabled: Raised if logging",
"Raised if logging is tried with out enabling logger in configurations Returns: logging.getLogger:",
"support safe logging. Args: logger_name (str): name given to current logger. level (int):",
"fire_watch from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename:",
"enabling logger in configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger =",
"logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT))",
"logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\")",
"logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level) logger.addHandler(file_handler) return logger raise",
"import fire_watch from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str,",
"def get_logger( logger_name: str, filename: str, level: int = 10, ) -> logging.getLogger:",
"FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level: int = 10,",
"configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler =",
"import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level: int",
"str, level: int = 10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented to",
"to. Raises: LogsNotEnabled: Raised if logging is tried with out enabling logger in",
"to throw all logs to. Raises: LogsNotEnabled: Raised if logging is tried with",
"severity level. filename (str): file to throw all logs to. Raises: LogsNotEnabled: Raised",
"safe logging. Args: logger_name (str): name given to current logger. level (int): severity",
"level: int = 10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented to support",
"\"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level) logger.addHandler(file_handler)",
"from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str,",
"= \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level: int = 10, )",
"implemented to support safe logging. Args: logger_name (str): name given to current logger.",
"logger_name: str, filename: str, level: int = 10, ) -> logging.getLogger: \"\"\"Simple logger",
"logger. level (int): severity level. filename (str): file to throw all logs to.",
"in configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler",
"Raises: LogsNotEnabled: Raised if logging is tried with out enabling logger in configurations",
"-> logging.getLogger: \"\"\"Simple logger configuration implemented to support safe logging. Args: logger_name (str):",
"name given to current logger. level (int): severity level. filename (str): file to",
"get_logger( logger_name: str, filename: str, level: int = 10, ) -> logging.getLogger: \"\"\"Simple",
"int = 10, ) -> logging.getLogger: \"\"\"Simple logger configuration implemented to support safe",
"file to throw all logs to. Raises: LogsNotEnabled: Raised if logging is tried",
"if logging is tried with out enabling logger in configurations Returns: logging.getLogger: logger",
"configuration implemented to support safe logging. Args: logger_name (str): name given to current",
"logging.getLogger: \"\"\"Simple logger configuration implemented to support safe logging. Args: logger_name (str): name",
"all logs to. Raises: LogsNotEnabled: Raised if logging is tried with out enabling",
"logging import fire_watch from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name:",
"level (int): severity level. filename (str): file to throw all logs to. Raises:",
"logger_name (str): name given to current logger. level (int): severity level. filename (str):",
"<filename>server/fire_watch/log/log_configs.py import logging import fire_watch from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def",
"given to current logger. level (int): severity level. filename (str): file to throw",
"LogsNotEnabled: Raised if logging is tried with out enabling logger in configurations Returns:",
"is tried with out enabling logger in configurations Returns: logging.getLogger: logger object \"\"\"",
"tried with out enabling logger in configurations Returns: logging.getLogger: logger object \"\"\" if",
"logging is tried with out enabling logger in configurations Returns: logging.getLogger: logger object",
"LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level: int =",
"throw all logs to. Raises: LogsNotEnabled: Raised if logging is tried with out",
"out enabling logger in configurations Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger",
"= logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level) logger.addHandler(file_handler) return logger raise LogsNotEnabled",
"if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level) logger.addHandler(file_handler) return",
"str, filename: str, level: int = 10, ) -> logging.getLogger: \"\"\"Simple logger configuration",
"\"\"\"Simple logger configuration implemented to support safe logging. Args: logger_name (str): name given",
"Returns: logging.getLogger: logger object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename,",
"import logging import fire_watch from fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger(",
"Args: logger_name (str): name given to current logger. level (int): severity level. filename",
"(str): file to throw all logs to. Raises: LogsNotEnabled: Raised if logging is",
"object \"\"\" if fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level)",
"fire_watch.conf[\"logs\"]: logger = logging.getLogger(logger_name) file_handler = logging.FileHandler(filename, mode=\"a\") file_handler.setFormatter(logging.Formatter(FMT)) file_handler.setLevel(level=level) logger.addHandler(file_handler) return logger",
"logs to. Raises: LogsNotEnabled: Raised if logging is tried with out enabling logger",
"logger configuration implemented to support safe logging. Args: logger_name (str): name given to",
"fire_watch.errorfactory import LogsNotEnabled FMT = \"%(asctime)s:%(name)s:%(message)s\" def get_logger( logger_name: str, filename: str, level:"
] |
[
"as pd ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict =",
"import List, Dict, Optional, Union, Any import pandas as pd ModelParam = Optional[Union[str,",
"List, Dict, Optional, Union, Any import pandas as pd ModelParam = Optional[Union[str, int,",
"Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str,",
"ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]]",
"Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str,",
"Dict, Optional, Union, Any import pandas as pd ModelParam = Optional[Union[str, int, float]]",
"typing import List, Dict, Optional, Union, Any import pandas as pd ModelParam =",
"import pandas as pd ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam]",
"from typing import List, Dict, Optional, Union, Any import pandas as pd ModelParam",
"List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict]",
"Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict",
"List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str, Any]] AllModelKwargsDict = Dict[str, AllModelKwargs]",
"ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame]",
"Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str, Any]] AllModelKwargsDict = Dict[str,",
"= Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict",
"= Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict",
"DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs",
"= Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs =",
"ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str, Any]] AllModelKwargsDict",
"pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str, Any]]",
"ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict,",
"Any import pandas as pd ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str,",
"Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict =",
"Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict =",
"int, float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict =",
"pandas as pd ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict",
"= Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict =",
"Union, Any import pandas as pd ModelParam = Optional[Union[str, int, float]] ParamDict =",
"float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]]",
"AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str, List[Any]] AllModelOptionPossibilitiesDict",
"= Dict[str, List[Any]] AllModelOptionPossibilitiesDict = Dict[str, ModelOptionPossibilitiesDict] AllModelKwargs = List[Dict[str, Any]] AllModelKwargsDict =",
"Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str, pd.DataFrame] ModelOptionPossibilitiesDict = Dict[str,",
"pd ModelParam = Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str,",
"Optional, Union, Any import pandas as pd ModelParam = Optional[Union[str, int, float]] ParamDict",
"float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str,",
"= Optional[Union[str, int, float]] ParamDict = Dict[str, ModelParam] ModelDict = Dict[str, Union[ParamDict, float]]",
"ModelParam] ModelDict = Dict[str, Union[ParamDict, float]] AllModelResultsDict = Dict[str, List[ModelDict]] DfDict = Dict[str,"
] |
[
"(Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False)",
"distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault to OK') self.r4.condition( 'transition {}",
"self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event):",
"'Aruba Networks' } class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1",
"License for the # specific language governing permissions and limitations # under the",
"event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition): _,",
"label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label = event['labels']",
"'System Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE):",
"software distributed under the License is distributed on an # \"AS IS\" BASIS,",
"this file except in compliance with the License. # You may obtain a",
"'/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2],",
"from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to",
"to OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 =",
"event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK",
"Rule('PSU status transition: OK to Output Fault') self.r1.condition( 'transition {} from \"ok\" to",
"event): label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event): label",
"'/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3],",
"self.r10 = Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\"",
"OK to Input Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input)",
"to Absent') def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu",
"coding: utf-8 -*- # # (c) Copyright 2018 Hewlett Packard Enterprise Development LP",
"= event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition): _, psu =",
"from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault",
"'2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\",
"' + transition) ActionSyslog(psu + ' status transition: ' + transition) ActionCLI('show environment",
"under the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES",
"'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?'",
"psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has",
"to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum",
"self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to",
"Rule('PSU status transition: OK to Input Fault') self.r2.condition( 'transition {} from \"ok\" to",
"from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to",
"\"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power",
"OR CONDITIONS OF ANY # KIND, either express or implied. See the License",
"language governing permissions and limitations # under the License. Manifest = { 'Name':",
"self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition:",
"Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 =",
"= Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition {} from \"ok\" to",
"Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def",
"to Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 =",
"status transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok)",
"to OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 =",
"from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault",
"OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status",
"self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition:",
"= event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event): label = event['labels']",
"implied. See the License for the # specific language governing permissions and limitations",
"[self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition {}",
"or agreed to in writing, # software distributed under the License is distributed",
"def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ')",
"{} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK",
"[self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in",
"label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label = event['labels']",
"Output Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def",
"status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label",
"= event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event): label = event['labels']",
"def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition",
"status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label",
"'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition:",
"'Input Fault to OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault",
"Input Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 =",
"either express or implied. See the License for the # specific language governing",
"2018 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License,",
"} class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1,",
"[self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {} from",
"Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def",
"event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label =",
"Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK to Output Fault') self.r1.condition(",
"= label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed from ' + transition)",
"= Rule('PSU status transition: Warning to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"',",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event):",
"= '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title(",
"\"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2,",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the",
"permissions and limitations # under the License. Manifest = { 'Name': 'power_supply_monitor', 'Description':",
"Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous",
"from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to",
"status transition: Warning to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok)",
"Development LP # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in",
"self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status",
"\"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault to OK') self.r6.condition(",
"status transition: Output Fault to OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"',",
"(c) Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed under the",
"to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault to OK')",
"= event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label,",
"self.logger.debug('PSU(' + psu + ') has changed from ' + transition) ActionSyslog(psu +",
"OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status",
"Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label =",
"has changed from ' + transition) ActionSyslog(psu + ' status transition: ' +",
"self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True)",
"is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"= Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"',",
"self.r5 = Rule('PSU status transition: Input Fault to OK') self.r5.condition( 'transition {} from",
"\\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title(",
"event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event): label",
"= Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power",
"= Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK",
"label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event): label =",
"OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self,",
"CONDITIONS OF ANY # KIND, either express or implied. See the License for",
"Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status",
"to OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def",
"uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1],",
"self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status",
"# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label,",
"status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"{} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2",
"def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event):",
"Output Fault to OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok)",
"express or implied. See the License for the # specific language governing permissions",
"and limitations # under the License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System",
"self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"{} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK",
"label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event): label =",
"License. # You may obtain a copy of the License at # #",
"-*- coding: utf-8 -*- # # (c) Copyright 2018 Hewlett Packard Enterprise Development",
"status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event):",
"transition: OK to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4",
"Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self,",
"self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum",
"from ' + transition) ActionSyslog(psu + ' status transition: ' + transition) ActionCLI('show",
"label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels']",
"Fault to OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6",
"License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"[self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to Warning') self.r3.condition('transition {} from",
"self.r4 = Rule('PSU status transition: Output Fault to OK') self.r4.condition( 'transition {} from",
"[self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault to OK') self.r6.condition( 'transition",
"compliance with the License. # You may obtain a copy of the License",
"Fault to OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK')",
"self.r6 = Rule('PSU status transition: Output Fault to OK') self.r6.condition( 'transition {} from",
"Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3,",
"self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault to OK') self.r5.condition( 'transition {}",
"event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label =",
"self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"= Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label",
"in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def",
"'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU",
"_, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed from '",
"= Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\",
"to Input Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Output",
"specific language governing permissions and limitations # under the License. Manifest = {",
"'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU",
"self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition {} from",
"Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed under the Apache",
"Output Fault to OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok)",
"or implied. See the License for the # specific language governing permissions and",
"Rule('PSU status transition: Input Fault to OK') self.r5.condition( 'transition {} from \"fault_input\" to",
"self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK",
"OK to Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2",
"uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power",
"label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition): _, psu",
"not use this file except in compliance with the License. # You may",
"'Absent to OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent')",
"distributed under the License is distributed on an # \"AS IS\" BASIS, WITHOUT",
"self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\",
"__init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition =",
"= '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power =",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown",
"to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU",
"event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label,",
"event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label =",
"= { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version': '2.0', 'Author':",
"# under the License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply",
"Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in",
"# specific language governing permissions and limitations # under the License. Manifest =",
"event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK",
"'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"),",
"= Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power",
"# you may not use this file except in compliance with the License.",
"status transition: Input Fault to OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"',",
"transition: OK to Input Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1])",
"{} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK",
"Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def",
"Unless required by applicable law or agreed to in writing, # software distributed",
"to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU",
"= event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label,",
"(the \"License\"); # you may not use this file except in compliance with",
"Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self):",
"label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label = event['labels']",
"title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels']",
"# KIND, either express or implied. See the License for the # specific",
"Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU",
"event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input",
"\"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to OK') self.r7.condition('transition {}",
"ANY # KIND, either express or implied. See the License for the #",
"to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault to OK')",
"= Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent",
"def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event):",
"{} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown",
"'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' }",
"\"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {}",
"\"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to Warning')",
"Fault to OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7",
"{} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent",
"file except in compliance with the License. # You may obtain a copy",
"\"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault to",
"to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU",
"from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to",
"+ ') has changed from ' + transition) ActionSyslog(psu + ' status transition:",
"in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power",
"See the License for the # specific language governing permissions and limitations #",
"label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed",
"{} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output",
"-*- # # (c) Copyright 2018 Hewlett Packard Enterprise Development LP # #",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"to OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def",
"OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU",
"'/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU",
"Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version': '2.0',",
"from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to",
"self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault to OK') self.r6.condition( 'transition {}",
"Output Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 =",
"\"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to OK')",
"= Rule('PSU status transition: OK to Output Fault') self.r1.condition( 'transition {} from \"ok\"",
"OK to Output Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output)",
"Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault')",
"self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to",
"to Output Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning')",
"KIND, either express or implied. See the License for the # specific language",
"monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self): uri1",
"\"License\"); # you may not use this file except in compliance with the",
"Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status')",
"to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to OK') self.r7.condition('transition",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output",
"Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK to",
"self.r1 = Rule('PSU status transition: OK to Output Fault') self.r1.condition( 'transition {} from",
"OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self,",
"\\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status",
"transition: Warning to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8",
"self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition:",
"event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label =",
"{ 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba",
"event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label,",
"= '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See",
"+ psu + ') has changed from ' + transition) ActionSyslog(psu + '",
"'OK to Absent') def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' +",
"Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"',",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"to OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK') def",
"{} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK",
"[self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault to OK') self.r4.condition( 'transition",
"Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault",
"transition: OK to Output Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1])",
"\"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {}",
"to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault to OK')",
"Networks' } class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 =",
"'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition:",
"Rule('PSU status transition: Output Fault to OK') self.r4.condition( 'transition {} from \"fault_output\" to",
"OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU",
"def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event):",
"= Rule('PSU status transition: OK to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"',",
"\"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault to",
"# -*- coding: utf-8 -*- # # (c) Copyright 2018 Hewlett Packard Enterprise",
"Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK to Output Fault') self.r1.condition( 'transition",
"Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK",
"self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK",
"# (c) Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed under",
"dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)')",
"[self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition {}",
"'OK to Output Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to",
"in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Input",
"# # Unless required by applicable law or agreed to in writing, #",
"to OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK')",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"),",
"for the # specific language governing permissions and limitations # under the License.",
"to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to Absent') self.r11.condition(",
"transition: OK to Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent)",
"title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK to Output",
"OF ANY # KIND, either express or implied. See the License for the",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied.",
"to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU",
"use this file except in compliance with the License. # You may obtain",
"transition: Input Fault to OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1])",
"\"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU status transition: Output Fault to",
"'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition:",
"Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?'",
"to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to Input Fault')",
"dashboard_display=True) self.r1 = Rule('PSU status transition: OK to Output Fault') self.r1.condition( 'transition {}",
"OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self,",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"= event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label,",
"Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the",
"transition: OK to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10",
"to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"psu + ') has changed from ' + transition) ActionSyslog(psu + ' status",
"transition: Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok)",
"title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3",
"{} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning",
"\"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to Unknown')",
"def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self,",
"'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU",
"status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label",
"status transition: OK to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning)",
"status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event): label",
"'Output Fault to OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to",
"status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition):",
"on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"status transition: OK to Input Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"',",
"self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?'",
"event): label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event): label",
"OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok) self.r6 = Rule('PSU",
"status transition: Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1])",
"to OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def",
"self.r2 = Rule('PSU status transition: OK to Input Fault') self.r2.condition( 'transition {} from",
"= Rule('PSU status transition: Output Fault to OK') self.r4.condition( 'transition {} from \"fault_output\"",
"OK to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 =",
"'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks'",
"writing, # software distributed under the License is distributed on an # \"AS",
"[self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {} from",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"[self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault to OK') self.r5.condition( 'transition",
"transition: Output Fault to OK') self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1])",
"\"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to OK')",
"Unknown to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 =",
"'Description': 'System Power Supply monitoring agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class",
"dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def",
"the License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent',",
"self.r7 = Rule('PSU status transition: Warning to OK') self.r7.condition('transition {} from \"warning\" to",
"class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status' self.m1 = Monitor(uri1, 'PSU",
"uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 = Monitor(uri3, 'instantaneous (Power in Watts)') self.graph_instantaneous",
"in Watts)') self.graph_max_power = Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3",
"Fault to OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to",
"transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed from",
"to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to Warning') self.r3.condition('transition",
"the License. # You may obtain a copy of the License at #",
"\"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition",
"Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version",
"limitations # under the License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power",
"status transition: OK to Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"', [self.m1])",
"\\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)') self.graph_max_power = Graph([self.m2], title=Title(",
"OK to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 =",
"Rule('PSU status transition: OK to Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1])",
"self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status",
"def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown') def status_fault_absent_to_ok(self, event):",
"self.r8 = Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\" to",
"\"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to Input Fault') self.r2.condition(",
"'Unknown to OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Unknown')",
"self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition {} from",
"{} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output",
"to OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 =",
"') has changed from ' + transition) ActionSyslog(psu + ' status transition: '",
"= Rule('PSU status transition: Input Fault to OK') self.r5.condition( 'transition {} from \"fault_input\"",
"= Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\" to",
"OK') def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self,",
"= Rule('PSU status transition: Output Fault to OK') self.r6.condition( 'transition {} from \"fault_output\"",
"label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed from ' + transition) ActionSyslog(psu",
"# # (c) Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed",
"with the License. # You may obtain a copy of the License at",
"\"PSU Status Transition\"), dashboard_display=True) self.r1 = Rule('PSU status transition: OK to Output Fault')",
"LP # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self,",
"OK') def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def",
"label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label = event['labels']",
"from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to",
"event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=')",
"'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition:",
"self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition:",
"'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self): uri1 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=status'",
"\"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to OK') self.r10.condition( 'transition",
"Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0",
"psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu + ') has changed from ' +",
"\"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to Warning') self.r3.condition('transition {}",
"Fault to OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5",
"'attributes=status' self.m1 = Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"),",
"'OK to Unknown') def status_fault_absent_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK')",
"'OK to Input Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to",
"to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown) self.r10 = Rule('PSU status transition: Absent to OK') self.r10.condition(",
"label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event): label =",
"'OK to Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to",
"def status_ok_to_fault_absent(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label,",
"self.r11 = Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition {} from \"ok\"",
"law or agreed to in writing, # software distributed under the License is",
"self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition:",
"# software distributed under the License is distributed on an # \"AS IS\"",
"status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event):",
"Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU",
"from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to",
"Absent to OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11",
"utf-8 -*- # # (c) Copyright 2018 Hewlett Packard Enterprise Development LP #",
"in compliance with the License. # You may obtain a copy of the",
"self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# Unless required by applicable law or agreed to in writing, # software",
"self.r9 = Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {} from \"ok\" to",
"self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self,",
"status transition: OK to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1]) self.r9.action(self.status_ok_to_unknown)",
"from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 =",
"to in writing, # software distributed under the License is distributed on an",
"agreed to in writing, # software distributed under the License is distributed on",
"transition: Output Fault to OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1])",
"OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
"Warning to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"to \"ok\"', [self.m1]) self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to Unknown') self.r9.condition('transition",
"self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\"",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"self.r8.action(self.status_unknown_to_ok) self.r9 = Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {} from \"ok\"",
"event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event): label",
"status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event):",
"event): label = event['labels'] self.psu_transition_action(label, 'Absent to OK') def status_ok_to_fault_absent(self, event): label =",
"\"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to Input",
"self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status transition: OK to Warning') self.r3.condition('transition {} from \"ok\"",
"Input Fault to OK') self.r5.condition( 'transition {} from \"fault_input\" to \"ok\"', [self.m1]) self.r5.action(self.status_fault_input_to_ok)",
"Absent') def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU(' + psu +",
"agent', 'Version': '2.0', 'Author': 'Aruba Networks' } class Agent(NAE): def __init__(self): uri1 =",
"the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Warning to OK') def status_unknown_to_ok(self, event): label",
"'transition {} from \"ok\" to \"fault_absent\"', [self.m1]) self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power'",
"Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to",
"= event['labels'] self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label,",
"\"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status transition: Output Fault to OK') self.r4.condition(",
"label = event['labels'] self.psu_transition_action(label, 'OK to Input Fault') def status_ok_to_fault_output(self, event): label =",
"to Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Input Fault to OK')",
"= event['labels'] self.psu_transition_action(label, 'Input Fault to OK') def status_fault_output_to_ok(self, event): label = event['labels']",
"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",
"\"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to OK')",
"to OK') self.r10.condition( 'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 =",
"the # specific language governing permissions and limitations # under the License. Manifest",
"under the License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring",
"self.psu_transition_action(label, 'OK to Absent') def psu_transition_action(self, label, transition): _, psu = label.split(',')[0].split('=') self.logger.debug('PSU('",
"in writing, # software distributed under the License is distributed on an #",
"def status_fault_output_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self,",
"# 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",
"to \"ok\"', [self.m1]) self.r7.action(self.status_warning_to_ok) self.r8 = Rule('PSU status transition: Unknown to OK') self.r8.condition('transition",
"Warning') self.r3.condition('transition {} from \"ok\" to \"warning\"', [self.m1]) self.r3.action(self.status_ok_to_warning) self.r4 = Rule('PSU status",
"self.psu_transition_action(label, 'Unknown to OK') def status_ok_to_unknown(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to",
"status transition: Output Fault to OK') self.r4.condition( 'transition {} from \"fault_output\" to \"ok\"',",
"self.r6.condition( 'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status",
"to Input Fault') self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3",
"\"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition: OK to Absent')",
"License. Manifest = { 'Name': 'power_supply_monitor', 'Description': 'System Power Supply monitoring agent', 'Version':",
"self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to OK') self.r7.condition('transition {} from \"warning\"",
"self.r3 = Rule('PSU status transition: OK to Warning') self.r3.condition('transition {} from \"ok\" to",
"self.r11.action(self.status_ok_to_fault_absent) uri2 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.maximum_power' self.m2 = Monitor(uri2, 'maximum (Power in Watts)')",
"Rule('PSU status transition: OK to Absent') self.r11.condition( 'transition {} from \"ok\" to \"fault_absent\"',",
"= Rule('PSU status transition: OK to Input Fault') self.r2.condition( 'transition {} from \"ok\"",
"[self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to Input Fault') self.r2.condition( 'transition",
"\"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self, event): label = event['labels'] self.psu_transition_action(label,",
"Rule('PSU status transition: Warning to OK') self.r7.condition('transition {} from \"warning\" to \"ok\"', [self.m1])",
"self.r2.condition( 'transition {} from \"ok\" to \"fault_input\"', [self.m1]) self.r2.action(self.status_ok_to_fault_input) self.r3 = Rule('PSU status",
"= event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event): label = event['labels'] self.psu_transition_action(label,",
"= Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"',",
"'transition {} from \"fault_absent\" to \"ok\"', [self.m1]) self.r10.action(self.status_fault_absent_to_ok) self.r11 = Rule('PSU status transition:",
"def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self, event):",
"Rule('PSU status transition: Unknown to OK') self.r8.condition('transition {} from \"unknown\" to \"ok\"', [self.m1])",
"{} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input",
"Monitor(uri1, 'PSU status') self.graph_status_transition = Graph([self.m1], title=Title( \"PSU Status Transition\"), dashboard_display=True) self.r1 =",
"status transition: OK to Output Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"',",
"\"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power' self.m3 =",
"required by applicable law or agreed to in writing, # software distributed under",
"self.r1.action(self.status_ok_to_fault_output) self.r2 = Rule('PSU status transition: OK to Input Fault') self.r2.condition( 'transition {}",
"Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False) def status_ok_to_fault_input(self,",
"(Power in Watts)') self.graph_instantaneous = Graph([self.m3], title=Title( \"PSU Instantaneous Power in Watts\"), dashboard_display=False)",
"+ transition) ActionSyslog(psu + ' status transition: ' + transition) ActionCLI('show environment power-supply')",
"changed from ' + transition) ActionSyslog(psu + ' status transition: ' + transition)",
"'Warning to OK') def status_unknown_to_ok(self, event): label = event['labels'] self.psu_transition_action(label, 'Unknown to OK')",
"Fault') def status_ok_to_warning(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Warning') def status_fault_input_to_ok(self,",
"by applicable law or agreed to in writing, # software distributed under the",
"to Output Fault') self.r1.condition( 'transition {} from \"ok\" to \"fault_output\"', [self.m1]) self.r1.action(self.status_ok_to_fault_output) self.r2",
"Rule('PSU status transition: OK to Unknown') self.r9.condition('transition {} from \"ok\" to \"unknown\"', [self.m1])",
"governing permissions and limitations # under the License. Manifest = { 'Name': 'power_supply_monitor',",
"the License for the # specific language governing permissions and limitations # under",
"applicable law or agreed to in writing, # software distributed under the License",
"Graph([self.m2], title=Title( \"PSU Maximum Power in Watts\"), dashboard_display=False) uri3 = '/rest/v1/system/subsystems/chassis/base/power_supplies/*?' \\ 'attributes=characteristics.instantaneous_power'",
"[self.m1]) self.r6.action(self.status_fault_output_to_ok) self.r7 = Rule('PSU status transition: Warning to OK') self.r7.condition('transition {} from",
"\"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition: Input Fault to OK') self.r5.condition(",
"Rule('PSU status transition: Output Fault to OK') self.r6.condition( 'transition {} from \"fault_output\" to",
"Input Fault') def status_ok_to_fault_output(self, event): label = event['labels'] self.psu_transition_action(label, 'OK to Output Fault')",
"event['labels'] self.psu_transition_action(label, 'Output Fault to OK') def status_warning_to_ok(self, event): label = event['labels'] self.psu_transition_action(label,",
"= event['labels'] self.psu_transition_action(label, 'OK to Output Fault') def status_ok_to_warning(self, event): label = event['labels']",
"'transition {} from \"fault_output\" to \"ok\"', [self.m1]) self.r4.action(self.status_fault_output_to_ok) self.r5 = Rule('PSU status transition:"
] |
[
"import admin from blog.models import get_model_factory from .posts_admin import PostAdmin # Register your",
"access page settings \"\"\" from django.contrib import admin from blog.models import get_model_factory from",
"from blog.models import get_model_factory from .posts_admin import PostAdmin # Register your models here.",
"settings \"\"\" from django.contrib import admin from blog.models import get_model_factory from .posts_admin import",
"\"\"\" Admin access page settings \"\"\" from django.contrib import admin from blog.models import",
"blog.models import get_model_factory from .posts_admin import PostAdmin # Register your models here. admin.site.register(get_model_factory('PostsFactory').create(),",
"from django.contrib import admin from blog.models import get_model_factory from .posts_admin import PostAdmin #",
"\"\"\" from django.contrib import admin from blog.models import get_model_factory from .posts_admin import PostAdmin",
"admin from blog.models import get_model_factory from .posts_admin import PostAdmin # Register your models",
"Admin access page settings \"\"\" from django.contrib import admin from blog.models import get_model_factory",
"import get_model_factory from .posts_admin import PostAdmin # Register your models here. admin.site.register(get_model_factory('PostsFactory').create(), PostAdmin)",
"django.contrib import admin from blog.models import get_model_factory from .posts_admin import PostAdmin # Register",
"page settings \"\"\" from django.contrib import admin from blog.models import get_model_factory from .posts_admin"
] |
[
"Done processing file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) #",
"output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile) # %%",
"jsonlines from multiprocessing.pool import ThreadPool import glob import json import os # %%",
"access OpenAire data # MUST end with a slash!!!! def process_one_file(outputName,inputFile): output =",
"print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files",
"# where to store and access OpenAire data # MUST end with a",
"import jsonlines from multiprocessing.pool import ThreadPool import glob import json import os #",
"data # MUST end with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\")",
"file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of",
"where to store and access OpenAire data # MUST end with a slash!!!!",
"os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for",
"%% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for i in",
"multiprocessing.pool import ThreadPool import glob import json import os # %% whereData =",
"print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\"))",
"OpenAire data # MUST end with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\")",
"def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile)",
"json import os # %% whereData = \"../OpenAire/publication/\" # where to store and",
"slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with",
"as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done",
"for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file:",
"import glob import json import os # %% whereData = \"../OpenAire/publication/\" # where",
"# %% whereData = \"../OpenAire/publication/\" # where to store and access OpenAire data",
"reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing",
"Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj))",
"= sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for i in allFiles: process_one_file(f\"{i}.2mkgc\",i)",
"= \"../OpenAire/publication/\" # where to store and access OpenAire data # MUST end",
"= open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for",
"os # %% whereData = \"../OpenAire/publication/\" # where to store and access OpenAire",
"output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj in",
"glob import json import os # %% whereData = \"../OpenAire/publication/\" # where to",
"import os # %% whereData = \"../OpenAire/publication/\" # where to store and access",
"# %% import jsonlines from multiprocessing.pool import ThreadPool import glob import json import",
"output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile) #",
"whereData = \"../OpenAire/publication/\" # where to store and access OpenAire data # MUST",
"\"../OpenAire/publication/\" # where to store and access OpenAire data # MUST end with",
"import ThreadPool import glob import json import os # %% whereData = \"../OpenAire/publication/\"",
"process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as",
"{inputFile} ...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all",
"print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj in reader:",
"sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for i in allFiles: process_one_file(f\"{i}.2mkgc\",i) print(\">>",
"open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj",
"...\") with jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\")",
"output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile)",
"from multiprocessing.pool import ThreadPool import glob import json import os # %% whereData",
"with jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close()",
"{inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{",
"processing file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List",
"file: {inputFile} ...\") with jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\")",
"ThreadPool import glob import json import os # %% whereData = \"../OpenAire/publication/\" #",
"<gh_stars>0 # %% import jsonlines from multiprocessing.pool import ThreadPool import glob import json",
"...\") print os.remove(inputFile) # %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the",
"reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile} ...\") print",
"MUST end with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing",
"# List of all the files for i in allFiles: process_one_file(f\"{i}.2mkgc\",i) print(\">> Done!\")",
"a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\")",
"import json import os # %% whereData = \"../OpenAire/publication/\" # where to store",
"jsonlines.open(inputFile) as reader: for obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">>",
"obj in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile}",
"}]\") output.close() print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles",
"# MUST end with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">>",
"to store and access OpenAire data # MUST end with a slash!!!! def",
"in reader: output.write(json.dumps(obj)) output.write(\",\\n\") output.write(\"{ }]\") output.close() print(f\">> Done processing file: {inputFile} ...\")",
"allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for i in allFiles:",
"output.close() print(f\">> Done processing file: {inputFile} ...\") print os.remove(inputFile) # %% allFiles =",
"output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile} ...\") with jsonlines.open(inputFile) as reader:",
"%% whereData = \"../OpenAire/publication/\" # where to store and access OpenAire data #",
"store and access OpenAire data # MUST end with a slash!!!! def process_one_file(outputName,inputFile):",
"with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file: {inputFile}",
"and access OpenAire data # MUST end with a slash!!!! def process_one_file(outputName,inputFile): output",
"%% import jsonlines from multiprocessing.pool import ThreadPool import glob import json import os",
"# %% allFiles = sorted(glob.glob(f\"{whereData}*.json\")) # List of all the files for i",
"end with a slash!!!! def process_one_file(outputName,inputFile): output = open(outputName,\"w\") output.write(\"[\\n\") print(f\">> Processing file:"
] |
[
"\"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] =",
"Python :: 3.7\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", install_requires=reqs, extras_require=extras_require, )",
"import setuptools with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() # #",
"can be found, the private package is installed. # import os # try:",
"The following code can be used if you have private dependencies. Basically it",
"to the private repository). If the env # # var cannot be found,",
"os.environ[\"GH_PAT\"] # except KeyError as e: # raise RuntimeError(\"You didn't set the environment",
"Personal Access Token (with access to the private repository). If the env #",
"your Personnal Access Token (from Github).\") from e # # Example of specifying",
"\"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\",",
"to a Github Personal Access Token (with access to the private repository). If",
"RuntimeError(\"You didn't set the environment variable `GH_PAT`. This is necessary because this package",
"these. Please set \" # \"`GH_PAT` environment variable to your Personnal Access Token",
"extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\",",
"long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating System",
"on private package(s), and you need to be authenticated to install these. Please",
"cannot be found, an error is raised. If it can be found, the",
"# # The following code can be used if you have private dependencies.",
"code can be used if you have private dependencies. Basically it requires the",
"be found, the private package is installed. # import os # try: #",
"set the environment variable `GH_PAT`. This is necessary because this package \" #",
"the environment variable `GH_PAT`. This is necessary because this package \" # \"relies",
"git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"],",
"`GH_PAT` to a Github Personal Access Token (with access to the private repository).",
"extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"you need to be authenticated to install these. Please set \" # \"`GH_PAT`",
":: Python :: 3.7\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", install_requires=reqs, extras_require=extras_require,",
"\"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"]",
"\" # \"relies on private package(s), and you need to be authenticated to",
"the env # # var cannot be found, an error is raised. If",
"package \" # \"relies on private package(s), and you need to be authenticated",
"try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e: # raise RuntimeError(\"You",
"extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python",
"extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\",",
"as e: # raise RuntimeError(\"You didn't set the environment variable `GH_PAT`. This is",
"packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating System :: OS Independent\",",
"= [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\",",
"private repository). If the env # # var cannot be found, an error",
"[] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\",",
"extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] +",
"[]) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup(",
"open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() # # The following code",
"\"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"]",
"be found, an error is raised. If it can be found, the private",
"# except KeyError as e: # raise RuntimeError(\"You didn't set the environment variable",
") setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\",",
"= os.environ[\"GH_PAT\"] # except KeyError as e: # raise RuntimeError(\"You didn't set the",
"the private package is installed. # import os # try: # gh_pat =",
"+ extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A",
"+ extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description,",
"except KeyError as e: # raise RuntimeError(\"You didn't set the environment variable `GH_PAT`.",
"\"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"]",
"be authenticated to install these. Please set \" # \"`GH_PAT` environment variable to",
"from e # # Example of specifying private dependencies : # reqs =",
"Please set \" # \"`GH_PAT` environment variable to your Personnal Access Token (from",
"# \"`GH_PAT` environment variable to your Personnal Access Token (from Github).\") from e",
"Token (with access to the private repository). If the env # # var",
"[\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\",",
"to set an # # environment variable `GH_PAT` to a Github Personal Access",
"specifying private dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = []",
"private dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require",
"error is raised. If it can be found, the private package is installed.",
"url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating System :: OS",
"\"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = (",
"to your Personnal Access Token (from Github).\") from e # # Example of",
"dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require =",
"package(s), and you need to be authenticated to install these. Please set \"",
"private package is installed. # import os # try: # gh_pat = os.environ[\"GH_PAT\"]",
"= [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\",",
"extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\",",
"fh: long_description = fh.read() # # The following code can be used if",
"because this package \" # \"relies on private package(s), and you need to",
"set \" # \"`GH_PAT` environment variable to your Personnal Access Token (from Github).\")",
"(from Github).\") from e # # Example of specifying private dependencies : #",
"# reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\":",
"with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() # # The following",
"# # Example of specifying private dependencies : # reqs = [f\"<package_name> @",
"env # # var cannot be found, an error is raised. If it",
"[\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), [])",
"variable `GH_PAT`. This is necessary because this package \" # \"relies on private",
"requires the user to set an # # environment variable `GH_PAT` to a",
"# Example of specifying private dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"]",
"Github).\") from e # # Example of specifying private dependencies : # reqs",
"Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating",
"Language :: Python :: 3.7\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", install_requires=reqs,",
"private dependencies. Basically it requires the user to set an # # environment",
"dependencies. Basically it requires the user to set an # # environment variable",
"import os # try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e:",
"Access Token (from Github).\") from e # # Example of specifying private dependencies",
"= { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"],",
"description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python",
"extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"os # try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e: #",
"package is installed. # import os # try: # gh_pat = os.environ[\"GH_PAT\"] #",
"\"Programming Language :: Python :: 3.7\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\",",
"you have private dependencies. Basically it requires the user to set an #",
"private package(s), and you need to be authenticated to install these. Please set",
"# import os # try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError as",
"# # environment variable `GH_PAT` to a Github Personal Access Token (with access",
"install these. Please set \" # \"`GH_PAT` environment variable to your Personnal Access",
"raised. If it can be found, the private package is installed. # import",
"the user to set an # # environment variable `GH_PAT` to a Github",
"access to the private repository). If the env # # var cannot be",
"raise RuntimeError(\"You didn't set the environment variable `GH_PAT`. This is necessary because this",
"version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming",
"\"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"],",
"+ extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template",
"to install these. Please set \" # \"`GH_PAT` environment variable to your Personnal",
"{ \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\":",
"This is necessary because this package \" # \"relies on private package(s), and",
"Example of specifying private dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs",
": # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = {",
"[\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] =",
"it requires the user to set an # # environment variable `GH_PAT` to",
"# try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e: # raise",
"gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e: # raise RuntimeError(\"You didn't set",
"of specifying private dependencies : # reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs =",
"an error is raised. If it can be found, the private package is",
"author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language ::",
"[\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] +",
"long_description = fh.read() # # The following code can be used if you",
"it can be found, the private package is installed. # import os #",
"as fh: long_description = fh.read() # # The following code can be used",
"# environment variable `GH_PAT` to a Github Personal Access Token (with access to",
"is raised. If it can be found, the private package is installed. #",
"# \"relies on private package(s), and you need to be authenticated to install",
"\" # \"`GH_PAT` environment variable to your Personnal Access Token (from Github).\") from",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating System ::",
"is installed. # import os # try: # gh_pat = os.environ[\"GH_PAT\"] # except",
"sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] )",
"found, an error is raised. If it can be found, the private package",
"encoding=\"utf-8\") as fh: long_description = fh.read() # # The following code can be",
"Personnal Access Token (from Github).\") from e # # Example of specifying private",
"classifiers=[ \"Programming Language :: Python :: 3.7\", \"Operating System :: OS Independent\", ],",
"the private repository). If the env # # var cannot be found, an",
"user to set an # # environment variable `GH_PAT` to a Github Personal",
"have private dependencies. Basically it requires the user to set an # #",
"environment variable `GH_PAT`. This is necessary because this package \" # \"relies on",
"name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[",
"`GH_PAT`. This is necessary because this package \" # \"relies on private package(s),",
"\"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"]",
"an # # environment variable `GH_PAT` to a Github Personal Access Token (with",
"environment variable `GH_PAT` to a Github Personal Access Token (with access to the",
"If the env # # var cannot be found, an error is raised.",
"if you have private dependencies. Basically it requires the user to set an",
"this package \" # \"relies on private package(s), and you need to be",
"Github Personal Access Token (with access to the private repository). If the env",
"[f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"],",
"If it can be found, the private package is installed. # import os",
"= ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\",",
"= sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"]",
"e: # raise RuntimeError(\"You didn't set the environment variable `GH_PAT`. This is necessary",
"# var cannot be found, an error is raised. If it can be",
"\"relies on private package(s), and you need to be authenticated to install these.",
"found, the private package is installed. # import os # try: # gh_pat",
"(with access to the private repository). If the env # # var cannot",
"Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python ::",
"used if you have private dependencies. Basically it requires the user to set",
"variable `GH_PAT` to a Github Personal Access Token (with access to the private",
"\"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] +",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language",
"KeyError as e: # raise RuntimeError(\"You didn't set the environment variable `GH_PAT`. This",
"\"r\", encoding=\"utf-8\") as fh: long_description = fh.read() # # The following code can",
"Access Token (with access to the private repository). If the env # #",
"reqs = [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\":",
"# The following code can be used if you have private dependencies. Basically",
"Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(), classifiers=[ \"Programming Language :: Python :: 3.7\",",
"repository). If the env # # var cannot be found, an error is",
"installed. # import os # try: # gh_pat = os.environ[\"GH_PAT\"] # except KeyError",
"} extras_require[\"all\"] = sum(extras_require.values(), []) extras_require[\"dev\"] = ( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"]",
"( extras_require[\"test\"] + extras_require[\"hook\"] + extras_require[\"lint\"] + extras_require[\"docs\"] ) setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\",",
"didn't set the environment variable `GH_PAT`. This is necessary because this package \"",
"and you need to be authenticated to install these. Please set \" #",
"# gh_pat = os.environ[\"GH_PAT\"] # except KeyError as e: # raise RuntimeError(\"You didn't",
"authenticated to install these. Please set \" # \"`GH_PAT` environment variable to your",
"# raise RuntimeError(\"You didn't set the environment variable `GH_PAT`. This is necessary because",
"set an # # environment variable `GH_PAT` to a Github Personal Access Token",
"= fh.read() # # The following code can be used if you have",
"setuptools with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() # # The",
"to be authenticated to install these. Please set \" # \"`GH_PAT` environment variable",
"var cannot be found, an error is raised. If it can be found,",
"following code can be used if you have private dependencies. Basically it requires",
"\"`GH_PAT` environment variable to your Personnal Access Token (from Github).\") from e #",
"fh.read() # # The following code can be used if you have private",
"\"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], } extras_require[\"all\"] = sum(extras_require.values(),",
"variable to your Personnal Access Token (from Github).\") from e # # Example",
"environment variable to your Personnal Access Token (from Github).\") from e # #",
"Token (from Github).\") from e # # Example of specifying private dependencies :",
"@ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\": [\"pytest~=7.0\", \"pytest-cov~=3.0\", \"coverage-badge~=1.0\"], \"hook\":",
"\"coverage-badge~=1.0\"], \"hook\": [\"pre-commit~=2.15\"], \"lint\": [\"isort~=5.9\", \"black~=22.1\", \"flake518~=1.2\", \"darglint~=1.8\"], \"docs\": [\"mkdocs-material~=8.1\", \"mkdocstrings[python]~=0.18\", \"mike~=1.1\"], }",
"Basically it requires the user to set an # # environment variable `GH_PAT`",
"setuptools.setup( name=\"pytere\", version=\"1.0.0.dev0\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A Python Template Repository\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/astariul/pytere\", packages=setuptools.find_packages(),",
"be used if you have private dependencies. Basically it requires the user to",
"e # # Example of specifying private dependencies : # reqs = [f\"<package_name>",
"necessary because this package \" # \"relies on private package(s), and you need",
"a Github Personal Access Token (with access to the private repository). If the",
"need to be authenticated to install these. Please set \" # \"`GH_PAT` environment",
"reqs = [f\"<package_name> @ git+https://{gh_pat}@github.com/<user>/<repo>@<tag>#egg=<package_name>\"] reqs = [] extras_require = { \"test\": [\"pytest~=7.0\",",
"can be used if you have private dependencies. Basically it requires the user",
"# # var cannot be found, an error is raised. If it can",
"is necessary because this package \" # \"relies on private package(s), and you"
] |
[
"return lid in self.mem def new_session(self, username: str, login_id: str): self.mem[login_id] = username",
"int: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return -1 # lowest",
"else '' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not (lid in",
"= request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else '' def get_friendly_name(self) ->",
"__init__(self): self.mem = {} return def check_user_status(self) -> bool: # to check whether",
"-> bool: # to check whether current user has logged in properly lid",
"import request class SessionManager: def __init__(self): self.mem = {} return def check_user_status(self) ->",
"def get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem",
"def check_user_status(self) -> bool: # to check whether current user has logged in",
"lid in self.mem def new_session(self, username: str, login_id: str): self.mem[login_id] = username return",
"current user has logged in properly lid = request.cookies.get('Login_ID') return lid in self.mem",
"SessionManager: def __init__(self): self.mem = {} return def check_user_status(self) -> bool: # to",
"in properly lid = request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username: str,",
"-> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else ''",
"UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not (lid in self.mem):",
"in self.mem def new_session(self, username: str, login_id: str): self.mem[login_id] = username return def",
"request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username: str, login_id: str): self.mem[login_id] =",
"request.cookies.get('Login_ID') if not (lid in self.mem): return -1 # lowest Privilege for Guests",
"= request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username: str, login_id: str): self.mem[login_id]",
"(lid in self.mem): return -1 # lowest Privilege for Guests return UserManager().get_privilege(self.mem[lid]) Login_Manager",
"request.cookies.get('Login_ID') if not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) ->",
"class SessionManager: def __init__(self): self.mem = {} return def check_user_status(self) -> bool: #",
"return def get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in",
"return self.mem[lid] if lid in self.mem else '' def get_friendly_name(self) -> str: lid",
"new_session(self, username: str, login_id: str): self.mem[login_id] = username return def get_username(self) -> str:",
"get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return -1",
"= request.cookies.get('Login_ID') if not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self)",
"get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else",
"self.mem else '' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not (lid",
"'' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not (lid in self.mem):",
"import UserManager from flask import request class SessionManager: def __init__(self): self.mem = {}",
"if lid in self.mem else '' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID')",
"self.mem = {} return def check_user_status(self) -> bool: # to check whether current",
"flask import request class SessionManager: def __init__(self): self.mem = {} return def check_user_status(self)",
"def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return",
"(lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid =",
"login_id: str): self.mem[login_id] = username return def get_username(self) -> str: lid = request.cookies.get('Login_ID')",
"properly lid = request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username: str, login_id:",
"in self.mem else '' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not",
"whether current user has logged in properly lid = request.cookies.get('Login_ID') return lid in",
"in self.mem): return -1 # lowest Privilege for Guests return UserManager().get_privilege(self.mem[lid]) Login_Manager =",
"if not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int:",
"not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid",
"def __init__(self): self.mem = {} return def check_user_status(self) -> bool: # to check",
"if not (lid in self.mem): return -1 # lowest Privilege for Guests return",
"from flask import request class SessionManager: def __init__(self): self.mem = {} return def",
"str: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid])",
"str): self.mem[login_id] = username return def get_username(self) -> str: lid = request.cookies.get('Login_ID') return",
"= request.cookies.get('Login_ID') if not (lid in self.mem): return -1 # lowest Privilege for",
"logged in properly lid = request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username:",
"= {} return def check_user_status(self) -> bool: # to check whether current user",
"bool: # to check whether current user has logged in properly lid =",
"return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not",
"get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return ''",
"self.mem): return -1 # lowest Privilege for Guests return UserManager().get_privilege(self.mem[lid]) Login_Manager = SessionManager()",
"username return def get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid",
"check_user_status(self) -> bool: # to check whether current user has logged in properly",
"from userManager import UserManager from flask import request class SessionManager: def __init__(self): self.mem",
"lid in self.mem else '' def get_friendly_name(self) -> str: lid = request.cookies.get('Login_ID') if",
"str: lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else '' def",
"lid = request.cookies.get('Login_ID') return lid in self.mem def new_session(self, username: str, login_id: str):",
"userManager import UserManager from flask import request class SessionManager: def __init__(self): self.mem =",
"to check whether current user has logged in properly lid = request.cookies.get('Login_ID') return",
"# to check whether current user has logged in properly lid = request.cookies.get('Login_ID')",
"{} return def check_user_status(self) -> bool: # to check whether current user has",
"has logged in properly lid = request.cookies.get('Login_ID') return lid in self.mem def new_session(self,",
"return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not (lid in",
"self.mem[login_id] = username return def get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid]",
"-> str: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return '' return",
"= username return def get_username(self) -> str: lid = request.cookies.get('Login_ID') return self.mem[lid] if",
"lid = request.cookies.get('Login_ID') if not (lid in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def",
"not (lid in self.mem): return -1 # lowest Privilege for Guests return UserManager().get_privilege(self.mem[lid])",
"UserManager from flask import request class SessionManager: def __init__(self): self.mem = {} return",
"in self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID')",
"def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return",
"check whether current user has logged in properly lid = request.cookies.get('Login_ID') return lid",
"self.mem): return '' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if",
"-> int: lid = request.cookies.get('Login_ID') if not (lid in self.mem): return -1 #",
"str, login_id: str): self.mem[login_id] = username return def get_username(self) -> str: lid =",
"request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else '' def get_friendly_name(self) -> str:",
"'' return UserManager().get_friendly_name(self.mem[lid]) def get_privilege(self) -> int: lid = request.cookies.get('Login_ID') if not (lid",
"return def check_user_status(self) -> bool: # to check whether current user has logged",
"lid = request.cookies.get('Login_ID') if not (lid in self.mem): return -1 # lowest Privilege",
"lid = request.cookies.get('Login_ID') return self.mem[lid] if lid in self.mem else '' def get_friendly_name(self)",
"self.mem def new_session(self, username: str, login_id: str): self.mem[login_id] = username return def get_username(self)",
"def new_session(self, username: str, login_id: str): self.mem[login_id] = username return def get_username(self) ->",
"self.mem[lid] if lid in self.mem else '' def get_friendly_name(self) -> str: lid =",
"<reponame>cmd2001/Open-TesutoHime from userManager import UserManager from flask import request class SessionManager: def __init__(self):",
"username: str, login_id: str): self.mem[login_id] = username return def get_username(self) -> str: lid",
"user has logged in properly lid = request.cookies.get('Login_ID') return lid in self.mem def",
"request class SessionManager: def __init__(self): self.mem = {} return def check_user_status(self) -> bool:"
] |
[
"cli from .services import Service from .context import Context from .types import set_group_name",
".main import cli from .services import Service from .context import Context from .types",
".services import Service from .context import Context from .types import set_group_name as group_name",
"from .services import Service from .context import Context from .types import set_group_name as",
"from .main import cli from .services import Service from .context import Context from",
"import cli from .services import Service from .context import Context from .types import"
] |
[
"map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian =",
"p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost =",
"location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n",
"= (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob",
"import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import pyplot",
"greedy(prob) # compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0])",
"map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30 degrees. #",
"# contour data over the map. if filled: base_color = np.array(to_rgb(col)) opp_color =",
"% meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native map",
"nlons = 291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta",
"delta = 2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats",
"import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import pyplot as plt",
"matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import pyplot as plt from",
"np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] =",
"lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for",
"Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c =",
"np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p =",
"nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) #",
"plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx",
"delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi)",
"lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten()))",
"cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy",
"u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native map projection coordinates of",
"= np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 +",
"lat/lon grid. # nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats",
"[\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else:",
"map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every",
"prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location of samples nx",
"make up some data on a regular lat/lon grid. # nlats = 145;",
"# draw lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"]",
"# compute native map projection coordinates of lat/lon grid. # x, y =",
"nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] #",
"from matplotlib.colors import to_rgb from matplotlib import pyplot as plt from mpl_toolkits.basemap import",
"i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0)",
"= 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons",
"mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if",
"2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs =",
"+ u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native map projection coordinates",
"def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c =",
"cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy = map((trueloc[0]*180./np.pi)-180.0, trueloc[1]*180./np.pi)",
"# make up some data on a regular lat/lon grid. # nlats =",
"grid. # nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats =",
"2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])",
"= 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs",
"meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data')",
"if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') #",
"- base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None:",
"skypost = cls(pts, trials=5, jobs=8) # make up some data on a regular",
"nlons = 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:])",
"pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8) # make up some data",
"# bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None:",
"map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy = map((trueloc[0]*180./np.pi)-180.0, trueloc[1]*180./np.pi) map.plot(xx,yy,marker='+',markersize=20,linewidth=5,color='black') return",
"import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c",
"[trueloc[0],trueloc[1]] if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white')",
"return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost",
"1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not",
"= skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location of samples nx =",
"greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1]",
"= c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] -",
"usetex=True) def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c",
"np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc =",
"= np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col)",
"= np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx]",
"c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls",
"matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density):",
"= np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p",
"291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons =",
"Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian",
"coordinates of lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x, y =",
"lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi)",
"x, y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data",
"np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if",
"from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def",
"#matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx])",
"compute native map projection coordinates of lat/lon grid. # x, y = map(lons*180./np.pi,",
"y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over",
"filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2",
"up some data on a regular lat/lon grid. # nlats = 145; nlons",
"np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute",
"= 2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats =",
"(0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob =",
"# x, y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour",
"to_rgb from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True)",
"projection coordinates of lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x, y",
"over the map. if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color",
"= np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0]",
"# compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz",
"30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\"",
"[np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is",
"map projection coordinates of lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x,",
"plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost = cls(pts, trials=5,",
"is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon",
"base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 =",
"import pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j",
"locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location",
"= ax # compute native map projection coordinates of lat/lon grid. # x,",
"matplotlib.colors import to_rgb from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap",
"= c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'):",
"lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) #",
"= map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the",
"if trueloc is not None: xx, yy = map((trueloc[0]*180./np.pi)-180.0, trueloc[1]*180./np.pi) map.plot(xx,yy,marker='+',markersize=20,linewidth=5,color='black') return map",
"= 145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons =",
"ax # compute native map projection coordinates of lat/lon grid. # x, y",
"= [trueloc[0],trueloc[1]] if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True)",
"= map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy =",
"data over the map. if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 -",
"cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8)",
"grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i",
"= pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8) # make up some",
"a regular lat/lon grid. # nlats = 145; nlons = 291; delta =",
"jobs=8) # make up some data on a regular lat/lon grid. # nlats",
"(delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob)",
"= map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy = map((trueloc[0]*180./np.pi)-180.0, trueloc[1]*180./np.pi) map.plot(xx,yy,marker='+',markersize=20,linewidth=5,color='black')",
"pts[:,0] = pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8) # make up",
"= cls(pts, trials=5, jobs=8) # make up some data on a regular lat/lon",
"c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:]",
"291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1)",
"mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx = np.argsort(density.flatten())[::-1]",
"= kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8) #",
"of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n =",
"= map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. if filled: base_color =",
"if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color])",
"p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0]",
"+ mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True)",
"contour data over the map. if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0",
"import numpy as np from ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors",
"# map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i]",
"np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j)",
"kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost = cls(pts, trials=5, jobs=8) # make",
"x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. if filled:",
"np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] =",
"map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx, yy = map((trueloc[0]*180./np.pi)-180.0,",
"p1 = greedy(prob) # compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny",
"= [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None: # map",
"lats*180./np.pi) # contour data over the map. if filled: base_color = np.array(to_rgb(col)) opp_color",
"[np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None: # map =",
"= 291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons = 291; delta =",
"import to_rgb from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text',",
"c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi",
"map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. if filled: base_color = np.array(to_rgb(col))",
"every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)):",
"= (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute",
"= np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc =",
"native map projection coordinates of lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi)",
"= np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location of",
"y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. if filled: base_color",
"# nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats = 145;",
"= greedy(prob) # compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny =",
"= Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30",
"np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))]",
"the map. if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1",
"base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is not None: xx,",
"np from ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from",
"map. if filled: base_color = np.array(to_rgb(col)) opp_color = 1.0 - base_color cs1 =",
"of lat/lon grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi,",
"np.pi skypost = cls(pts, trials=5, jobs=8) # make up some data on a",
"draw lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1])",
"i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax",
"145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons = 291;",
"mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1])",
"= (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 =",
"from ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib",
"map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map",
"= 145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons",
"lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in",
"numpy as np from ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import",
"# map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines",
"meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native map projection",
"grid. # x, y = map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) #",
"as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density)",
"lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. if",
"skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0])",
"compute mean location of samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz =",
"- np.pi skypost = cls(pts, trials=5, jobs=8) # make up some data on",
"c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def",
"opp_color = 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc",
"else: map = ax # compute native map projection coordinates of lat/lon grid.",
"as np from ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb",
"= Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30 degrees. # map.drawmeridians(np.arange(0,360,30))",
"kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import pyplot as",
"nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc",
"in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax #",
"# lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons)",
"nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1) nlats = 145; nlons",
"pyplot as plt from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j =",
"= np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return",
"= 1.0 - base_color cs1 = map.contourf(x,y,1.0-p1,levels=[0.0,0.1,0.5,1.0],colors=[base_color+opp_color,base_color+0.8*opp_color,base_color+0.6*opp_color,base_color]) cs2 = map.contour(x,y,p1,levels=[0.5,0.9],linewidths=2.0,colors=col) if trueloc is",
"np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]]",
"map = ax # compute native map projection coordinates of lat/lon grid. #",
"bestloc = [trueloc[0],trueloc[1]] if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map =",
"p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE",
"lons = (delta*np.indices((nlats,nlons))[1,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1",
"data on a regular lat/lon grid. # nlats = 145; nlons = 291;",
"samples nx = np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)]",
"cls(pts, trials=5, jobs=8) # make up some data on a regular lat/lon grid.",
"= np.cos(pts[:,1])*np.cos(pts[:,0]) ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc",
"degrees. # map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" %",
"np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean location of samples",
"on a regular lat/lon grid. # nlats = 145; nlons = 291; delta",
"map.drawmeridians(np.arange(0,360,30)) meridian = [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] +",
"None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid",
"mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map",
"= [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax",
"from mpl_toolkits.basemap import Basemap #matplotlib.rc('text', usetex=True) def greedy(density): i,j = np.shape(density) idx =",
"np.append(c,1.0) p = np.zeros(i*j) p[idx] = c[:] return p.reshape(i,j) def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls =",
"matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import pyplot as plt from mpl_toolkits.basemap",
"some data on a regular lat/lon grid. # nlats = 145; nlons =",
"map(lons*180./np.pi, lats*180./np.pi) x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the map.",
"trials=5, jobs=8) # make up some data on a regular lat/lon grid. #",
"Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every 30 degrees.",
"def plot_sky(pts,contour=True,filled=False,ax=None,trueloc=None,cmap='Reds',col='red'): cls = kde.Clustered2DSkyKDE pts[:,0] = pts[:,0] - np.pi skypost = cls(pts,",
"idx = np.argsort(density.flatten())[::-1] c = np.cumsum(density.flatten()[idx]) c = c/c[-1] np.append(c,1.0) p = np.zeros(i*j)",
"= [\"-180\",\"-150\",\"-120\",\"-90\",\"-60\",\"-30\",\"0\",\"30\",\"+60\",\"+90\",\"+120\",\"+150\"] map.drawmeridians(np.arange(-180,180,30),labels=[1,1,1,1]) for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])",
"145; nlons = 291; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) # lons =",
"map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native map projection coordinates of lat/lon",
"regular lat/lon grid. # nlats = 145; nlons = 291; delta = 2.*np.pi/(nlons-1)",
"ligo.skymap import kde import matplotlib matplotlib.use('Agg') from matplotlib.colors import to_rgb from matplotlib import",
"ax is None: # map = Basemap(projection='ortho',lon_0=-bestloc[0]*180/np.pi,lat_0=bestloc[1]*180/np.pi,resolution=None,celestial=True) map = Basemap(projection='moll',lon_0=0,resolution=None,celestial=True) map.drawmapboundary(fill_color='white') # draw",
"bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2 + mean_n[1]**2))] bestloc = [trueloc[0],trueloc[1]] if ax is None: #",
"plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map = ax # compute native",
"(delta*np.indices((nlats,nlons))[1,:,:]-np.pi) locs = np.column_stack((lons.flatten(),lats.flatten())) prob = skypost(locs).reshape(nlats,nlons) p1 = greedy(prob) # compute mean",
"for i in np.arange(len(meridian)): plt.annotate(r\"$\\textrm{%s}$\" % meridian[i] + u\"\\u00b0\",xy=map(np.arange(-180,180,30)[i],0),xycoords='data') map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]) else: map =",
"ny = np.cos(pts[:,1])*np.sin(pts[:,0]) nz = np.sin(pts[:,1]) mean_n = [np.mean(nx),np.mean(ny),np.mean(nz)] # bestloc = [np.remainder(np.arctan2(mean_n[1],mean_n[0]),2.0*np.pi),np.arctan2(mean_n[2],np.sqrt(mean_n[0]**2"
] |
[
"# TEKDB/apps.py from django.apps import AppConfig class TEKDBConfig(AppConfig): name = 'TEKDB' verbose_name =",
"TEKDB/apps.py from django.apps import AppConfig class TEKDBConfig(AppConfig): name = 'TEKDB' verbose_name = 'Records'"
] |
[
"<reponame>baby5/HackerRank<filename>DataStructures/LinkedList/CycleDetection.py #coding:utf-8 def has_cycle(head): ptr1 = head ptr2 = head while ptr2 and",
"= head while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if",
"ptr1 = head ptr2 = head while ptr2 and ptr1.next: ptr1 = ptr1.next.next",
"def has_cycle(head): ptr1 = head ptr2 = head while ptr2 and ptr1.next: ptr1",
"has_cycle(head): ptr1 = head ptr2 = head while ptr2 and ptr1.next: ptr1 =",
"ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1 is ptr2: return 1",
"= ptr1.next.next ptr2 = ptr2.next if ptr1 is ptr2: return 1 return 0",
"and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1 is ptr2: return",
"ptr2 = head while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next",
"head while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1",
"while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1 is",
"= head ptr2 = head while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2",
"#coding:utf-8 def has_cycle(head): ptr1 = head ptr2 = head while ptr2 and ptr1.next:",
"ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1 is ptr2:",
"ptr1 = ptr1.next.next ptr2 = ptr2.next if ptr1 is ptr2: return 1 return",
"head ptr2 = head while ptr2 and ptr1.next: ptr1 = ptr1.next.next ptr2 ="
] |
[
"def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds:",
"save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) -> None: if self.last_epoch ==",
"client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0]",
"self, build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu: bool = True,",
"add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2,",
"History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int):",
"-> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs",
"tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds,",
"Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a",
"Callable, global_batch_size: int, split: str, data_augmentation: Callable = lambda x, y: (x, y),",
"Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool):",
"TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import storage from typing import Callable,",
"max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self,",
"y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size",
"dataset class Training: def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str =",
"] def _setup_model(self, build_model: Callable) -> None: if self.last_epoch == 0: self.model =",
"build_model: Callable) -> None: if self.last_epoch == 0: self.model = build_model() else: checkpoint",
"tensorflow as tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud",
"\"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) -> None: if self.last_epoch",
"== \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE)",
"preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable = lambda x, y: (x,",
"= [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def",
"dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option",
"x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing",
"tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with",
"in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1),",
"checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks)",
"List import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str,",
"dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE)",
"Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu: bool = True, ) ->",
"if self.last_epoch == 0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model =",
".batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda",
"valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2):",
"lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names",
"tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) -> None:",
"else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\"",
"Callable) -> None: if self.last_epoch == 0: self.model = build_model() else: checkpoint =",
"dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or",
"# Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks =",
"data_augmentation: Callable = lambda x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args:",
"\"\"\" # Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset(",
"file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split == \"train\": option.experimental_deterministic",
"build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client",
"= \"\", use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func",
"== 0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def",
"True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス.",
"[0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch",
"job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management",
"drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self, build_model_func: Callable, job_dir:",
"self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"),",
"str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable = lambda x, y:",
"artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster setup",
"class Training: def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\",",
"dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\"",
"return last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds:",
"def _get_last_epoch(self) -> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\",",
"= tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option =",
"y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True",
"= tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope",
"\\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class",
"artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir =",
"run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う.",
"self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う.",
"found: {dataset}\") option = tf.data.Options() if split == \"train\": option.experimental_deterministic = False dataset",
"Callable, List import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split:",
"TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset",
"self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) ->",
"= tf.data.Options() if split == \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\",
"num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self,",
"in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return",
"def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable =",
"import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation:",
"epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) -> None:",
"-> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir",
"tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\"",
"blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs: epoch =",
"FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names = tf.io.gfile.glob(",
"tf.data.Options() if split == \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda",
"_setup_model(self, build_model: Callable) -> None: if self.last_epoch == 0: self.model = build_model() else:",
"dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable = lambda x,",
"= b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self,",
"tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks",
"epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def",
"train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit(",
"tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options()",
"from google.cloud import storage from typing import Callable, List import os def get_tfrecord_dataset(",
"train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合.",
"split: str, data_augmentation: Callable = lambda x, y: (x, y), ) -> TFRecordDatasetV2:",
"(Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable, optional):",
"storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints",
"Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [",
"(Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\"",
"TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用).",
"option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda",
"global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults",
"use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す.",
"= dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y))",
"バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x.",
"checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client()",
"= dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return",
"{dataset}\") option = tf.data.Options() if split == \"train\": option.experimental_deterministic = False dataset =",
"job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch =",
"\"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str):",
"preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable,",
"-> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計).",
"実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" #",
"from typing import Callable, List import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable,",
"import tensorflow as tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from",
"(x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数.",
"dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b",
"self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ]",
"for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch =",
") -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする.",
"self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2]",
"bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints =",
"storage from typing import Callable, List import os def get_tfrecord_dataset( dataset_path: str, preprocessing:",
"tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model:",
"distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(),",
"example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\",
"split == \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example),",
"job_dir: str, artifacts_dir: str = \"\", use_tpu: bool = True, ) -> None:",
"get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable = lambda",
"= self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster)",
"data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン.",
"os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int, split: str, data_augmentation: Callable",
"with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir,",
"\"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス.",
"self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if",
"= True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False)",
"int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs =",
") ] def _setup_model(self, build_model: Callable) -> None: if self.last_epoch == 0: self.model",
"not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split == \"train\":",
"raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split == \"train\": option.experimental_deterministic =",
"blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch",
"None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str):",
"setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in",
"file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if",
"= self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in",
"tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import storage",
"preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__(",
"tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with self.distribute_strategy.scope():",
"num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True)",
"def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu: bool",
".batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self, build_model_func: Callable,",
"tensorflow.python.keras.callbacks import History from google.cloud import storage from typing import Callable, List import",
"self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True,",
") -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用).",
"= lambda x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str):",
"= use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster =",
"複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history",
"def _setup_model(self, build_model: Callable) -> None: if self.last_epoch == 0: self.model = build_model()",
"= tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func)",
"# Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names,",
"callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs:",
"dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\",
") dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\")",
"(int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if",
"tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs",
"prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if",
"def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する.",
"str = \"\", use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments:",
"\"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs: epoch",
"実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir = job_dir self.artifacts_dir",
"(bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir",
"a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if",
"tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not",
"split (str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises:",
"(Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\"",
".map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE)",
"目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation",
"cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy",
"f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found:",
"dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset",
"(int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to",
"DLトレーニングで共通のロジック・モジュール import tensorflow as tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History",
"if split == \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda example:",
"self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster)",
"global_batch_size: int, split: str, data_augmentation: Callable = lambda x, y: (x, y), )",
"typing import Callable, List import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size:",
"else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client =",
"lambda x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス.",
"checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir",
"Callable = lambda x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path",
"= build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest",
"トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if self.artifacts_dir:",
"(str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir = job_dir",
"= job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu:",
"Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train",
"= False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x,",
"import Callable, List import os def get_tfrecord_dataset( dataset_path: str, preprocessing: Callable, global_batch_size: int,",
"(TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds,",
"str, data_augmentation: Callable = lambda x, y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する.",
"self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" )",
"use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir = job_dir self.artifacts_dir =",
"import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import storage from typing import",
"[ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self,",
"= [0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch))",
"TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu",
"\\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example),",
"y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic",
"\"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if self.artifacts_dir: self.model.save(f\"{self.artifacts_dir}/saved_model\",",
"pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not",
"histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable)",
"client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name,",
"int, split: str, data_augmentation: Callable = lambda x, y: (x, y), ) ->",
"(str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For job",
"= self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0]",
"import History from google.cloud import storage from typing import Callable, List import os",
"= tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise",
"0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self)",
"True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\",
"# For job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu",
"\"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数.",
"-> None: if self.last_epoch == 0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\"",
"self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if self.artifacts_dir: self.model.save(f\"{self.artifacts_dir}/saved_model\", include_optimizer=False) return history",
"num_parallel_reads=tf.data.AUTOTUNE) if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split",
"= storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\")",
".shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset =",
"Training: def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu:",
"TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split",
"dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x,",
"use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver()",
"\\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self, build_model_func:",
"build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu: bool = True, )",
"last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def",
"file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE) if not file_names:",
"drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda example:",
"\\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\",
".map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training:",
"TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds",
"management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch()",
"option = tf.data.Options() if split == \"train\": option.experimental_deterministic = False dataset = dataset.with_options(option)",
"= client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\",",
"import storage from typing import Callable, List import os def get_tfrecord_dataset( dataset_path: str,",
"history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if self.artifacts_dir: self.model.save(f\"{self.artifacts_dir}/saved_model\", include_optimizer=False)",
"build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest =",
"\"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List)",
"valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2:",
"y: (x, y), ) -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable):",
"History from google.cloud import storage from typing import Callable, List import os def",
"valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks,",
"from tensorflow.python.keras.callbacks import History from google.cloud import storage from typing import Callable, List",
"(str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError:",
"# DLトレーニングで共通のロジック・モジュール import tensorflow as tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import",
"optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" #",
"Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load",
"self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for",
"Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history =",
"None: if self.last_epoch == 0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model",
"self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu",
"cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model",
"\\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512,",
"artifacts_dir: str = \"\", use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う.",
"str, artifacts_dir: str = \"\", use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う.",
"self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster)",
"= True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str):",
"For job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch",
"None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) ->",
"self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs = client.list_blobs(bucket_name, prefix=f\"{dest}/checkpoints\") checkpoints = [0] for b in blobs:",
"preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size,",
"\"\", use_tpu: bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable):",
"if not file_names: raise FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split ==",
"option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size,",
"int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds (TFRecordDatasetV2):",
"as tf from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import",
"train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments:",
"epochs: int ) -> History: \"\"\"トレーニングを実施し、ログや結果を保存する. tf.keras.Model.fitでのトレーニングを行う. 複雑なトレーニングループが必要な場合もtf.keras.Model.train_stepをオーバーライドするなどして使う. Arguments: train_ds (TFRecordDatasetV2): tensorflowのデータセットパイプライン(学習用). valid_ds",
"return dataset class Training: def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str",
"tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) ->",
"scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\", histogram_freq=1), tf.keras.callbacks.TerminateOnNaN(), tf.keras.callbacks.ModelCheckpoint(",
"self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int ) -> History:",
"from tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import storage from",
"self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else:",
"to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline",
"Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names =",
"x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else:",
"Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" )",
"= max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train(",
"Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset = tf.data.TFRecordDataset( file_names, num_parallel_reads=tf.data.AUTOTUNE)",
"-> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\") blobs",
"data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic =",
"or valid data_augmentation (Callable, optional): データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns:",
"filepath=os.path.join(self.job_dir, \"checkpoints/{epoch:05d}\"), save_weights_only=True, save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) -> None: if",
"self.last_epoch == 0: self.model = build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint)",
"False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y:",
"else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\",
"トレーニングにTPUを使うかどうか. \"\"\" # For job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu",
"job_dir self.artifacts_dir = artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: #",
".map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .map(lambda x, y: data_augmentation(x, y)) \\ .shuffle(512, reshuffle_each_iteration=True)",
"b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints)",
"\\ .shuffle(512, reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset",
"checkpoints = [0] for b in blobs: epoch = b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch:",
"データオーグメンテーション関数. Defaults to lambdax:x. Raises: FileNotFoundError: dataset_pathにファイルが存在しない場合. Returns: TFRecordDatasetV2: 定義済みのデータパイプライン. \"\"\" # Build",
"= build_model() else: checkpoint = f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int:",
"epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs )",
"-> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int )",
"\"train\": option.experimental_deterministic = False dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\",
".prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\ .map(lambda example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE)",
"= self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch, epochs=epochs ) if self.artifacts_dir: self.model.save(f\"{self.artifacts_dir}/saved_model\", include_optimizer=False) return",
"\\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option) \\",
"__init__( self, build_model_func: Callable, job_dir: str, artifacts_dir: str = \"\", use_tpu: bool =",
"FileNotFoundError(f\"Not found: {dataset}\") option = tf.data.Options() if split == \"train\": option.experimental_deterministic = False",
"= f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client() bucket_name",
"\\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self, build_model_func: Callable, job_dir: str,",
"job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか. \"\"\" # For",
"save_freq=\"epoch\" ) ] def _setup_model(self, build_model: Callable) -> None: if self.last_epoch == 0:",
"bool = True, ) -> None: \"\"\"トレーニングの初期設定を行う. TPUノードの管理、TPUStrategyの設定、モデルのロード、コンパイル、checkpointの復旧などを行う. Arguments: build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir",
"\"\"\" # For job management self.job_dir = job_dir self.artifacts_dir = artifacts_dir self.use_tpu =",
"tensorflow.python.data.ops.readers import TFRecordDatasetV2 from tensorflow.python.keras.callbacks import History from google.cloud import storage from typing",
"self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy",
"= artifacts_dir self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster",
"tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) # Load model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func)",
"model in distribute_strategy scope with self.distribute_strategy.scope(): self._setup_model(build_model=build_model_func) else: self._setup_model(build_model=build_model_func) self.callbacks = [ tf.keras.callbacks.TensorBoard(log_dir=f\"{self.job_dir}/logs\",",
"if self.use_tpu: # Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy =",
"example: preprocessing(example=example), num_parallel_calls=tf.data.AUTOTUNE) \\ .batch(global_batch_size, drop_remainder=False) \\ .prefetch(tf.data.AUTOTUNE) return dataset class Training: def",
"# Tpu cluster setup cluster = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(cluster) tf.tpu.experimental.initialize_tpu_system(cluster) self.distribute_strategy = tf.distribute.TPUStrategy(cluster) #",
"reshuffle_each_iteration=True) \\ .batch(global_batch_size, drop_remainder=True) \\ .prefetch(tf.data.AUTOTUNE) else: option.experimental_deterministic = True dataset = dataset.with_options(option)",
"build_model_func (Callable): 実験に使うモデルのbuild関数を渡す. job_dir (str): job管理用のGCSパス. checkpointやlogの保存をする. artifacts_dir (str): 実験結果の保存先GCSパス. use_tpu (bool): トレーニングにTPUを使うかどうか.",
") -> TFRecordDatasetV2: \"\"\"TFRecordからデータパイプラインを構築する. Args: dataset_path (str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int):",
"(TFRecordDatasetV2): tensorflowのデータセットパイプライン(検証用). epochs (int): トレーニングを回す合計エポック数. \"\"\" history = self.model.fit( train_ds, validation_data=valid_ds, callbacks=self.callbacks, initial_epoch=self.last_epoch,",
".prefetch(tf.data.AUTOTUNE) return dataset class Training: def __init__( self, build_model_func: Callable, job_dir: str, artifacts_dir:",
"b.name.replace(f\"{dest}/checkpoints/\", \"\").split(\".\")[0] if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks:",
"f\"{self.job_dir}/checkpoints/{self.last_epoch:0>5}\" self.model = build_model(checkpoint=checkpoint) def _get_last_epoch(self) -> int: client = storage.Client() bucket_name =",
"List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2, valid_ds: TFRecordDatasetV2, epochs: int",
"if epoch: checkpoints.append(int(epoch)) last_epoch = max(checkpoints) return last_epoch def add_callbacks(self, callbacks: List) ->",
"self.use_tpu = use_tpu self.last_epoch = self._get_last_epoch() if self.use_tpu: # Tpu cluster setup cluster",
"_get_last_epoch(self) -> int: client = storage.Client() bucket_name = self.job_dir.split(\"/\")[2] dest = self.job_dir.replace(f\"gs://{bucket_name}/\", \"\")",
"定義済みのデータパイプライン. \"\"\" # Build a pipeline file_names = tf.io.gfile.glob( f\"{dataset_path}/{split}-*.tfrec\" ) dataset =",
"適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid data_augmentation (Callable, optional): データオーグメンテーション関数.",
"google.cloud import storage from typing import Callable, List import os def get_tfrecord_dataset( dataset_path:",
"(str): 目的のTFRecordファイルが保存されているパス. preprocessing (Callable): 適用する前処理関数. global_batch_size (int): バッチサイズ(分散処理の場合は合計). split (str): train or valid",
"last_epoch def add_callbacks(self, callbacks: List) -> None: self.callbacks.extend(callbacks) def run_train( self, train_ds: TFRecordDatasetV2,"
] |
[
"in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel",
"np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv = np.array([u,",
"translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\ depth[depth",
"depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters ---------- depth : numpy.ndarray",
": cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4",
"image. Parameters ---------- depth : numpy.ndarray depth image in meter order. bgr_cameramodel :",
"depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray",
"to color image. Parameters ---------- depth : numpy.ndarray depth image in meter order.",
"numpy.ndarray depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel :",
"bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray",
"> 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv,",
"= np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv =",
"cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation",
"transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0] !=",
"cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img :",
"depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth))",
"uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame",
"depth : numpy.ndarray depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel",
"\\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height,",
"image to color image. Parameters ---------- depth : numpy.ndarray depth image in meter",
"- np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)]",
"cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned",
"depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] =",
"= bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\ depth[depth > 0][indices] return aligned_img",
"np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] =",
"\"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth",
"np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3]",
"image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError",
"translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame =",
"depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T",
": numpy.ndarray depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel",
"= np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3,",
"u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation =",
"numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\" if",
"depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters ---------- depth",
"meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform",
"align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters ----------",
"aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv",
"xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) -",
"depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T,",
"uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3,",
"depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy()",
"= np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame =",
"depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters ---------- depth : numpy.ndarray depth",
"Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\",
"depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img =",
"4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0]",
"= depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul(",
"!= depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img",
"-1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\ depth[depth >",
"0 v, u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3]",
": numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] !=",
"= depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul(",
"numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width:",
"xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices =",
"= 0 v, u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3,",
"depth image to color image. Parameters ---------- depth : numpy.ndarray depth image in",
"rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\",
"color image. Parameters ---------- depth : numpy.ndarray depth image in meter order. bgr_cameramodel",
"aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise",
"= depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u =",
"------- aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or",
"order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform :",
":3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame",
"import numpy as np def align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image",
"---------- depth : numpy.ndarray depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr",
"depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel",
"np def align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image.",
"bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix.",
"rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\ depth[depth > 0][indices]",
"dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation",
"or depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width),",
"depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0])",
"v, u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation",
"\"\"\"Align depth image to color image. Parameters ---------- depth : numpy.ndarray depth image",
"cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns",
"= (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel(",
"as np def align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color",
"if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1] != depth_cameramodel.width: raise ValueError depth =",
"depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T,",
"indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True) aligned_img.reshape(-1)[bgr_cameramodel.flatten_uv(rgb_uv)] = \\ depth[depth > 0][indices] return",
"bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv = np.array([u, v]).T",
"aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height \\ or depth.shape[1]",
"bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters ---------- depth :",
"= depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth >",
"matrix. Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\" if depth.shape[0] != depth_cameramodel.height",
"raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0",
"3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth > 0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T)",
"depth_cameramodel : cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns -------",
"v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv,",
"Parameters ---------- depth : numpy.ndarray depth image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel",
"image in meter order. bgr_cameramodel : cameramodels.PinholeCameraModel bgr cameramodel depth_cameramodel : cameramodels.PinholeCameraModel depth",
": cameramodels.PinholeCameraModel depth cameramodel depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img",
"0]) xyz_rgb_frame = (np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices",
"depth.shape[1] != depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32)",
"depth_to_rgb_transform : numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned image.",
"!= depth_cameramodel.width: raise ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)]",
"depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v, u",
"numpy as np def align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to",
"ValueError depth = depth.copy() aligned_img = np.zeros((bgr_cameramodel.height, bgr_cameramodel.width), dtype=np.float32) depth[np.isnan(depth)] = 0 v,",
"np.array([u, v]).T rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray(",
"depth[np.isnan(depth)] = 0 v, u = np.array(np.where(depth)) uv = np.array([u, v]).T rotation =",
"xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True, return_indices=True)",
"rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame, project_valid_depth_only=True,",
"rotation = depth_to_rgb_transform[:3, :3] translation = depth_to_rgb_transform[:3, 3] xyz_depth_frame = depth_cameramodel.batch_project_pixel_to_3d_ray( uv, depth=depth[depth",
"(np.matmul( rotation.T, xyz_depth_frame.T) - np.matmul( rotation.T, translation).reshape(3, -1)).T rgb_uv, indices = bgr_cameramodel.batch_project3d_to_pixel( xyz_rgb_frame,",
"def align_depth_to_rgb( depth, bgr_cameramodel, depth_cameramodel, depth_to_rgb_transform): \"\"\"Align depth image to color image. Parameters",
": numpy.ndarray 4x4 transformation matrix. Returns ------- aligned_img : numpy.ndarray aligned image. \"\"\""
] |
[
"'Lorem ipsum 2' } ] def get_credentials(app_id): return [cred for cred in [",
"if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for app in get_credentials('20001') if",
"-*- coding: utf-8 -*- def info(): return { 'country': 'FR', 'firstname': 'John', 'legalform':",
"None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2",
"'description': 'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name':",
"'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber':",
"'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city':",
"'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration':",
"'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area':",
"{ 'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path': '/*' }, {",
"cred in [ { 'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path': '/*'",
"'<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ] def get_credentials(app_id):",
"app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for app",
"get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for app in get_credentials('20001')",
"'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann' } def get_applications(): return",
"{ 'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method':",
"'59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix',",
"'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email':",
"'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann' } def get_applications():",
"'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ] def get_credentials(app_id): return [cred for",
"'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber':",
"}, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum",
"[cred for cred in [ { 'ovhSupport': False, 'rules': [ { 'method': 'GET',",
"], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00'",
"def get_application(app_id): return next((app for app in get_applications() if app['applicationId'] == int(app_id))) def",
"{ 'method': 'POST', 'path': '/*' }, { 'method': 'PUT', 'path': '/*' }, {",
"next((app for app in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app",
"None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100',",
"'2 rue Kellermann' } def get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>',",
"'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True,",
"'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey':",
"def info(): return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency':",
"'2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app",
"'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann' } def get_applications(): return [",
"<filename>tests/fixtures/me.py<gh_stars>10-100 # -*- coding: utf-8 -*- def info(): return { 'country': 'FR', 'firstname':",
"'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax':",
"{ 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002,",
"'', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete',",
"'', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR',",
"'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2',",
"'/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00',",
"'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] ==",
"'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' },",
"'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId':",
"'path': '/*' }, { 'method': 'POST', 'path': '/*' }, { 'method': 'PUT', 'path':",
"20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ] def get_credentials(app_id): return [cred",
"def get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1',",
"'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann' }",
"} ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse':",
"'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ] def get_credentials(app_id): return",
"'/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated',",
"3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem",
"def get_credential(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def",
"'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ] def",
"'<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status': 'active',",
"20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>',",
"for cred in [ { 'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path':",
"}, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId':",
"50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)]",
"get_credential(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id):",
"info(): return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': {",
"False, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path':",
"app in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for app",
"'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany':",
"'vat': '', 'address': '2 rue Kellermann' } def get_applications(): return [ { 'status':",
"'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002,",
"'/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated',",
"'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00',",
"== int(app_id))) def get_credential(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] ==",
"'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address':",
"next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app",
"'<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None,",
"in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for app in",
"'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status':",
"ipsum 2' } ] def get_credentials(app_id): return [cred for cred in [ {",
"'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' },",
"'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, {",
"'path': '/*' }, { 'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path':",
"app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for app in get_credentials('20001') if app['credentialId']",
"'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001,",
"] def get_credentials(app_id): return [cred for cred in [ { 'ovhSupport': False, 'rules':",
"rue Kellermann' } def get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId':",
"{ 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail':",
"'', 'address': '2 rue Kellermann' } def get_applications(): return [ { 'status': 'active',",
"'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR',",
"'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def",
"'Roubaix', 'vat': '', 'address': '2 rue Kellermann' } def get_applications(): return [ {",
"if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for app in get_credentials('20001') if",
"in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for app in",
"# -*- coding: utf-8 -*- def info(): return { 'country': 'FR', 'firstname': 'John',",
"'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' },",
"'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00',",
"'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for",
"None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann'",
"1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem",
"{ 'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ],",
"return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem",
"'/*' }, { 'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*'",
"'2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path':",
"'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType':",
"{ 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001,",
"ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description':",
"'description': 'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name':",
"20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def get_application(app_id):",
"'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '',",
"'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3',",
"'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST',",
"'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex':",
"'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol':",
"return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code':",
"get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description':",
"} ] def get_credentials(app_id): return [cred for cred in [ { 'ovhSupport': False,",
"'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' } ]",
"] if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for app in get_applications()",
"None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None,",
"2' } ] def get_credentials(app_id): return [cred for cred in [ { 'ovhSupport':",
"'foobar-2', 'description': 'Lorem ipsum 2' } ] def get_credentials(app_id): return [cred for cred",
"for app in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for",
"'+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '',",
"get_credentials(app_id): return [cred for cred in [ { 'ovhSupport': False, 'rules': [ {",
"'', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>',",
"'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status':",
"return next((app for app in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return",
"'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId':",
"'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId':",
"'<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status': 'active',",
"'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '',",
"'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle':",
"'2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path': '/*' },",
"'/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00',",
"None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None,",
"[ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum",
"None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue Kellermann' } def",
"20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ { 'method':",
"}, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789',",
"'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity':",
"'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None,",
"'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh',",
"'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None,",
"'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport':",
"'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003,",
"[ { 'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path': '/*' }, {",
"in [ { 'ovhSupport': False, 'rules': [ { 'method': 'GET', 'path': '/*' },",
"None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh',",
"{ 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR',",
"'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None,",
"{ 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2'",
"'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '', 'phone':",
"'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat':",
"'address': '2 rue Kellermann' } def get_applications(): return [ { 'status': 'active', 'applicationKey':",
"int(credential_id))) def get_rules(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id)))['rules']",
"} ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse':",
"int(app_id)] def get_application(app_id): return next((app for app in get_applications() if app['applicationId'] == int(app_id)))",
"'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, { 'status':",
"def get_credentials(app_id): return [cred for cred in [ { 'ovhSupport': False, 'rules': [",
"'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay':",
"}, { 'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE', 'path': '/*' }",
"'2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, {",
"'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ { 'method': 'GET',",
"'path': '/*' }, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status':",
"ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description':",
"== int(credential_id))) def get_rules(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] ==",
"'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation':",
"'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' }",
"'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1' }, {",
"'description': 'Lorem ipsum 2' } ] def get_credentials(app_id): return [cred for cred in",
"get_application(app_id): return next((app for app in get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id):",
"}, { 'method': 'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId':",
"'POST', 'path': '/*' }, { 'method': 'PUT', 'path': '/*' }, { 'method': 'DELETE',",
"}, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum",
"'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules':",
"{ 'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method':",
"True, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path':",
"}, { 'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path': '/*' }, {",
"Kellermann' } def get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001,",
"'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO'",
"'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation':",
"return [cred for cred in [ { 'ovhSupport': False, 'rules': [ { 'method':",
"50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [",
"], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00'",
"'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId':",
"'John', 'legalform': 'individual', 'name': 'Doe', 'currency': { 'code': 'EUR', 'symbol': 'EURO' }, 'ovhSubsidiary':",
"} ] if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for app in",
"'method': 'POST', 'path': '/*' }, { 'method': 'PUT', 'path': '/*' }, { 'method':",
"'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey':",
"int(app_id))) def get_credential(credential_id): return next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id)))",
"'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ {",
"cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for app in get_applications() if app['applicationId']",
"'fr_FR', 'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None,",
"'symbol': 'EURO' }, 'ovhSubsidiary': 'FR', 'birthDay': None, 'organisation': '', 'spareEmail': None, 'area': '',",
"[ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path': '/*' },",
"'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation': '2016-08-03T17:52:21+02:00', 'lastUse': '2016-08-03T17:51:12+02:00' },",
"'lastUse': '2016-08-03T17:51:12+02:00' }, { 'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path': '/*'",
"'ovhSupport': True, 'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST',",
"'DELETE', 'path': '/*' } ], 'expiration': '2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001,",
"'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20002, 'name': 'foobar-2', 'description': 'Lorem ipsum 2' }",
"20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3' }, { 'status': 'active', 'applicationKey': '<KEY>',",
"'2016-08-04T17:47:33+02:00', 'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ]",
"'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def get_application(app_id): return",
"'2016-08-03T17:50:23+02:00' } ] if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for app",
"'area': '', 'phone': '+33.123456789', 'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language':",
"'GET', 'path': '/*' }, { 'method': 'POST', 'path': '/*' }, { 'method': 'PUT',",
"return next((app for app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return",
"'path': '/*' } ], 'expiration': '2016-08-04T17:52:21+02:00', 'status': 'validated', 'credentialId': 50000002, 'applicationId': 20001, 'creation':",
"get_applications() if app['applicationId'] == int(app_id))) def get_credential(credential_id): return next((app for app in get_credentials('20001')",
"utf-8 -*- def info(): return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name':",
"'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if cred['applicationId']",
"coding: utf-8 -*- def info(): return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual',",
"-*- def info(): return { 'country': 'FR', 'firstname': 'John', 'legalform': 'individual', 'name': 'Doe',",
"if cred['applicationId'] == int(app_id)] def get_application(app_id): return next((app for app in get_applications() if",
"'nationalIdentificationNumber': None, 'ovhCompany': 'ovh', 'email': '<EMAIL>', 'companyNationalIdentificationNumber': None, 'language': 'fr_FR', 'fax': '', 'zip':",
"'rules': [ { 'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path': '/*'",
"'fax': '', 'zip': '59100', 'nichandle': 'dj12345-ovh', 'corporationType': None, 'sex': None, 'birthCity': None, 'state':",
"'sex': None, 'birthCity': None, 'state': 'complete', 'city': 'Roubaix', 'vat': '', 'address': '2 rue",
"'status': 'validated', 'credentialId': 50000001, 'applicationId': 20001, 'creation': '2016-08-03T17:47:33+02:00', 'lastUse': '2016-08-03T17:50:23+02:00' } ] if",
"{ 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20003, 'name': 'foobar-3', 'description': 'Lorem ipsum 3'",
"'/*' }, { 'method': 'POST', 'path': '/*' }, { 'method': 'PUT', 'path': '/*'",
"'method': 'GET', 'path': '/*' }, { 'method': 'POST', 'path': '/*' }, { 'method':",
"== int(app_id)] def get_application(app_id): return next((app for app in get_applications() if app['applicationId'] ==",
"for app in get_credentials('20001') if app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for",
"{ 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name': 'foobar-1', 'description': 'Lorem ipsum 1'",
"}, { 'method': 'POST', 'path': '/*' }, { 'method': 'PUT', 'path': '/*' },",
"app['credentialId'] == int(credential_id))) def get_rules(credential_id): return next((app for app in get_credentials('20001') if app['credentialId']",
"} def get_applications(): return [ { 'status': 'active', 'applicationKey': '<KEY>', 'applicationId': 20001, 'name':"
] |
[] |
[
"exist, or already attached # attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName)",
"pass # happens when app not known, or app already attached to mote",
"\\brief Publishes the data into the DustLinkData database. One instance of this class",
"'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #======================== public ========================================== #======================== private =========================================",
"local variables #======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData()",
"or app already attached to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'],",
"exists # in demo mode, add demo mode apps to mote if dld.getDemoMode():",
"_publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if needed try:",
"DustLinkData import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the",
"for each application. ''' def __init__(self,appName): # store params self._appName = appName #",
"========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if",
"= logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData import DustLinkData from",
"the data into the DustLinkData database. One instance of this class is created",
"dld.addMote(data['mac']) except ValueError: pass # happens when mote already exists # in demo",
"apps to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError:",
"One instance of this class is created for each application. ''' def __init__(self,appName):",
"params self._appName = appName # log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self,",
"emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from",
"import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data",
"import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler())",
"self._appName = appName # log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName),",
"try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app does not exist, or",
"# initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add",
"already exists # in demo mode, add demo mode apps to mote if",
"import copy import threading from DustLinkData import DustLinkData from EventBus import EventBusClient class",
"ValueError: pass # happens when app not known, or app already attached to",
"log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData import DustLinkData from EventBus import",
"EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables",
"if needed try: dld.addMote(data['mac']) except ValueError: pass # happens when mote already exists",
") self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #======================== public ==========================================",
"DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac']) except ValueError:",
"class is created for each application. ''' def __init__(self,appName): # store params self._appName",
"instance of this class is created for each application. ''' def __init__(self,appName): #",
"# log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name",
"def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if needed",
"happens when app does not exist, or already attached # attach app to",
"needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app not known, or",
"# store params self._appName = appName # log log.info('creating instance') # initialize parent",
"mote if needed try: dld.addMote(data['mac']) except ValueError: pass # happens when mote already",
"self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #======================== public",
"initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats",
"add mote if needed try: dld.addMote(data['mac']) except ValueError: pass # happens when mote",
"def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading",
"in demo mode, add demo mode apps to mote if dld.getDemoMode(): for appname",
"mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass #",
"import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the DustLinkData database.",
"'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #========================",
"= 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #======================== public ========================================== #======================== private",
"appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app does",
"log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName)",
"not dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac']) except ValueError: pass #",
"pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData import",
"DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into",
"attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens",
"# add mote if needed try: dld.addMote(data['mac']) except ValueError: pass # happens when",
"log.addHandler(NullHandler()) import copy import threading from DustLinkData import DustLinkData from EventBus import EventBusClient",
"stats # local variables #======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld",
"except ValueError: pass # happens when mote already exists # in demo mode,",
"''' def __init__(self,appName): # store params self._appName = appName # log log.info('creating instance')",
"mode apps to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except",
"happens when mote already exists # in demo mode, add demo mode apps",
"# publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) # log if log.isEnabledFor(logging.DEBUG):",
"from DustLinkData import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes",
"attached to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) #",
"of this class is created for each application. ''' def __init__(self,appName): # store",
"def __init__(self,appName): # store params self._appName = appName # log log.info('creating instance') #",
"for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app",
"# in demo mode, add demo mode apps to mote if dld.getDemoMode(): for",
"class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy",
"#======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not",
"instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) #",
"in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app does not",
"in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) # log if log.isEnabledFor(logging.DEBUG): log.debug('published {0}'.format(data))",
"''' \\brief Publishes the data into the DustLinkData database. One instance of this",
"# happens when app not known, or app already attached to mote #",
"#!/usr/bin/python import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR)",
"pass # happens when app does not exist, or already attached # attach",
"import threading from DustLinkData import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): '''",
"app already attached to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'],",
"logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import",
"demo mode, add demo mode apps to mote if dld.getDemoMode(): for appname in",
"NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import",
"ValueError: pass # happens when app does not exist, or already attached #",
"logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData import DustLinkData from EventBus",
"store params self._appName = appName # log log.info('creating instance') # initialize parent class",
"add stats # local variables #======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data):",
"into the DustLinkData database. One instance of this class is created for each",
"private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote",
"mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app not",
"application. ''' def __init__(self,appName): # store params self._appName = appName # log log.info('creating",
"or already attached # attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except",
"app not known, or app already attached to mote # publish in DustLinkData",
"DustLinkData database. One instance of this class is created for each application. '''",
"app does not exist, or already attached # attach app to mote if",
"attached # attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass",
"dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when",
"the DustLinkData database. One instance of this class is created for each application.",
"parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats #",
"data into the DustLinkData database. One instance of this class is created for",
"# local variables #======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld =",
"already attached to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], )",
"record): pass log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData",
"when app does not exist, or already attached # attach app to mote",
"EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the DustLinkData database. One",
"#======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add",
"dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app not known, or app already",
"class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local",
"log = logging.getLogger('AppDataPublisher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import copy import threading from DustLinkData import DustLinkData",
"needed try: dld.addMote(data['mac']) except ValueError: pass # happens when mote already exists #",
"class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the DustLinkData database. One instance",
"mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) # log if",
"dld = DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac'])",
"# happens when mote already exists # in demo mode, add demo mode",
"does not exist, or already attached # attach app to mote if needed",
"copy import threading from DustLinkData import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient):",
"to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) # log",
"app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when",
"Publishes the data into the DustLinkData database. One instance of this class is",
"if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app not known,",
"mote already exists # in demo mode, add demo mode apps to mote",
"if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens",
"# add stats # local variables #======================== public ========================================== #======================== private ========================================= def",
"mode, add demo mode apps to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys():",
"= DustLinkData.DustLinkData() if not dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac']) except",
"try: dld.addMote(data['mac']) except ValueError: pass # happens when mote already exists # in",
"except ValueError: pass # happens when app not known, or app already attached",
"not known, or app already attached to mote # publish in DustLinkData dld.indicateData(data['mac'],",
"to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app",
"# happens when app does not exist, or already attached # attach app",
"each application. ''' def __init__(self,appName): # store params self._appName = appName # log",
"is created for each application. ''' def __init__(self,appName): # store params self._appName =",
"variables #======================== public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if",
"pass # happens when mote already exists # in demo mode, add demo",
"when mote already exists # in demo mode, add demo mode apps to",
"threading from DustLinkData import DustLinkData from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief",
"from EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the",
"AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the DustLinkData database. One instance of",
"========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode(): #",
"appName # log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, )",
"EventBus import EventBusClient class AppDataPublisher(EventBusClient.EventBusClient): ''' \\brief Publishes the data into the DustLinkData",
"public ========================================== #======================== private ========================================= def _publish(self,sender,signal,data): dld = DustLinkData.DustLinkData() if not dld.getFastMode():",
"# attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass #",
"= appName # log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish,",
"known, or app already attached to mote # publish in DustLinkData dld.indicateData(data['mac'], self._appName,",
"dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac']) except ValueError: pass # happens",
"database. One instance of this class is created for each application. ''' def",
"ValueError: pass # happens when mote already exists # in demo mode, add",
"created for each application. ''' def __init__(self,appName): # store params self._appName = appName",
"already attached # attach app to mote if needed try: dld.attachAppToMote(data['mac'],self._appName) except ValueError:",
"try: dld.attachAppToMote(data['mac'],self._appName) except ValueError: pass # happens when app not known, or app",
"this class is created for each application. ''' def __init__(self,appName): # store params",
"except ValueError: pass # happens when app does not exist, or already attached",
"demo mode apps to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname)",
"log log.info('creating instance') # initialize parent class EventBusClient.EventBusClient.__init__(self, 'parsedAppData_{0}'.format(self._appName), self._publish, ) self.name =",
"when app not known, or app already attached to mote # publish in",
"self.name = 'DataConnector_AppDataPublisher_{0}'.format(self._appName) # add stats # local variables #======================== public ========================================== #========================",
"happens when app not known, or app already attached to mote # publish",
"to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass",
"dld.DEMO_MODE_APPS.keys(): try: dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app does not exist,",
"not exist, or already attached # attach app to mote if needed try:",
"dld.attachAppToMote(data['mac'],appname) except ValueError: pass # happens when app does not exist, or already",
"__init__(self,appName): # store params self._appName = appName # log log.info('creating instance') # initialize",
"publish in DustLinkData dld.indicateData(data['mac'], self._appName, data['fields'], timestamp=data['timestamp'], ) # log if log.isEnabledFor(logging.DEBUG): log.debug('published",
"add demo mode apps to mote if dld.getDemoMode(): for appname in dld.DEMO_MODE_APPS.keys(): try:",
"if not dld.getFastMode(): # add mote if needed try: dld.addMote(data['mac']) except ValueError: pass"
] |
[
"DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test,",
"DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return",
"DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit'))",
"import unittest from Sastrawi.Morphology.Disambiguator.DisambiguatorPrefixRule1 import DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a =",
"self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur')) if __name__",
"= DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit',",
"def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur')) if __name__ ==",
"test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur')) if __name__ == '__main__':",
"Sastrawi.Morphology.Disambiguator.DisambiguatorPrefixRule1 import DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b =",
"super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur')) if",
"self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self):",
"setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia',",
"from Sastrawi.Morphology.Disambiguator.DisambiguatorPrefixRule1 import DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b",
"def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self):",
"Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def",
"self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia'))",
"class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp()",
"unittest from Sastrawi.Morphology.Disambiguator.DisambiguatorPrefixRule1 import DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a()",
"DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def",
"= DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b() return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari'))",
"import DisambiguatorPrefixRule1a, DisambiguatorPrefixRule1b class Test_DisambiguatorPrefixRule1Test(unittest.TestCase): def setUp(self): self.subject1a = DisambiguatorPrefixRule1a() self.subject1b = DisambiguatorPrefixRule1b()",
"return super(Test_DisambiguatorPrefixRule1Test, self).setUp() def test_disambiguate1a(self): self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur'))",
"self.assertEquals('ia-ia', self.subject1a.disambiguate('beria-ia')) self.assertIsNone(self.subject1a.disambiguate('berlari')) def test_disambiguate1b(self): self.assertEquals('rakit', self.subject1b.disambiguate('berakit')) self.assertIsNone(self.subject1b.disambiguate('bertabur')) if __name__ == '__main__': unittest.main()"
] |
[
"requests import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content)",
"for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']:",
"TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path,",
"js['repositories'] != None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for",
"None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in",
"json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag)",
"IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path)",
"tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path =",
"'{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True)",
"= '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path +",
"change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path], universal_newlines=True) subprocess.check_output(['docker', 'push', change_image_path],",
"= json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000",
"import subprocess import requests import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr))",
"port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr",
"subprocess import requests import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js",
"+ '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories'] != None: for v",
"json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if",
"js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host,",
":5000 if js['repositories'] != None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if",
"tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port,",
"print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path],",
"for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host,",
"image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path",
"= '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path],",
"in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path =",
"<filename>move.py<gh_stars>0 import subprocess import requests import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r =",
"host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' +",
"\"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path], universal_newlines=True) subprocess.check_output(['docker',",
"print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list'",
"new_port = '' #ex) :5000 if js['repositories'] != None: for v in js['repositories']:",
"= '' #ex) :5000 if js['repositories'] != None: for v in js['repositories']: tag_request",
"'/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories'] != None: for v in",
"'' #ex) :5000 if js['repositories'] != None: for v in js['repositories']: tag_request =",
"tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag)",
"IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag',",
"in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v,",
"= json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v,",
"subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path], universal_newlines=True) subprocess.check_output(['docker', 'push', change_image_path], universal_newlines=True)",
"tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port,",
"import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js)",
"PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker',",
"#ex) :5000 if js['repositories'] != None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content)",
"if js['repositories'] != None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']:",
"'{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\"",
"v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag in tag_request['tags']: image_path",
"if tag_request['tags']: for tag in tag_request['tags']: image_path = '{HOST}:{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path",
"change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull',",
"PORT=port, IMAGE_NAME=v, TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" +",
"url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories'] != None: for",
"TAG=tag) change_image_path = '{HOST}{PORT}/{IMAGE_NAME}:{TAG}'.format(HOST=host, PORT=new_port, IMAGE_NAME=v, TAG=tag) print(image_path + \"-->\" + change_image_path) subprocess.check_output(['docker',",
"+ url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories'] != None:",
"+ change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path], universal_newlines=True) subprocess.check_output(['docker', 'push',",
"json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://'",
"url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr +",
"js = json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex)",
"!= None: for v in js['repositories']: tag_request = json.loads(requests.get(tag_format.format(IMAGE_NAME=v)).content) if tag_request['tags']: for tag",
"= requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port =",
"r = requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port",
"+ \"-->\" + change_image_path) subprocess.check_output(['docker', 'pull', image_path], universal_newlines=True) subprocess.check_output(['docker', 'tag', image_path, change_image_path], universal_newlines=True)",
"import requests import json host='registry.host.com' port='16443' url_addr='{}:{}/v2'.format(host,port) print(url_addr) r = requests.get('https://{}/_catalog'.format(url_addr)) js =",
"requests.get('https://{}/_catalog'.format(url_addr)) js = json.loads(r.content) #print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = ''",
"tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories'] !=",
"#print(js) tag_format='https://' + url_addr + '/{IMAGE_NAME}/tags/list' new_port = '' #ex) :5000 if js['repositories']"
] |
[
"Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp']",
"template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv', index=False)",
"template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data",
"tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999)",
"= 15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6,",
"= Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] =",
"the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB",
"'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation',",
"template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID']",
"# indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity',",
"'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv')",
"df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID']",
"types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] =",
"['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction',",
"Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv')",
"= template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] =",
"template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID']",
"df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15",
"= RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999)",
"pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv')",
"template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int)",
"hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df],",
"df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10",
"df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15,",
"Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data",
"= Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] =",
"'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols =",
"df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3, df_4, df_5,",
"df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time",
"8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12",
"1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added '''",
"= 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added",
"pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time',",
"= Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] =",
"ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin =",
"pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv')",
"7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11",
"RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction",
"= Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999)",
"header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout",
"'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) #",
"= ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols]",
"template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID']",
"= 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] =",
"pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv')",
"template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] =",
"# read templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path",
"= pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12,",
"9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13",
"Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79",
"tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH']",
"79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex",
"df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols =",
"template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes)",
"df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin",
"ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum())",
"df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID']",
"'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df",
"= df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] =",
"template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID']",
"df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity']",
"''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2',",
"Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into",
"Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True)",
"df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5",
"= Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False,",
"= df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout =",
"'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature',",
"Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv')",
"'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation',",
"tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID']",
"= pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] =",
"df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID']",
"15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7,",
"df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time",
"= pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 =",
"4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8",
"RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999)",
"tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID']",
"header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols =",
"Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity']",
"['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation',",
"tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time']",
"print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] =",
"change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\")",
"= pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv')",
"Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) '''",
"hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] =",
"= pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int)",
"df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0']",
"= CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False,",
"pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac =",
"Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout",
"tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed:",
"+ 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 =",
"'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed',",
"format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] =",
"tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time",
"tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df =",
"1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change",
"Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID",
"= pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999)",
"tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp']",
"tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed: 0':",
"Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID",
"tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2']",
"Gao/_yapan_processing/' # read templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor =",
"= 1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) #",
"df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16],",
"numpy as np import os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79",
"ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status',",
"= df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True)",
"df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID']",
"'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID']",
"13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df = pd.concat([df_1,",
"pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in",
"1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time']",
"= 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] =",
"'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df =",
"df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID']",
"= pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check data",
"df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11",
"pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13,",
"= ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df],",
"'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols",
"= pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 =",
"df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed:",
"df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID']",
"df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement",
"save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num",
"pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed",
"= 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] =",
"Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction",
"tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv',",
"= pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 =",
"outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID']",
"0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2']",
"template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path",
"= pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 =",
"df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16",
"= df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction =",
"df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID']",
"Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout",
"os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/'",
"tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction']",
"print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time']",
"= 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num =",
"= 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] =",
"hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes)",
"= template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path +",
"= pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 =",
"tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement",
"= 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df =",
"= template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] =",
"import os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT",
"template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int)",
"pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2",
"tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] =",
"79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num = pd.read_csv(template_path +",
"= pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 =",
"df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin =",
"df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature']",
"template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int)",
"df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13",
"= df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] =",
"df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df",
"tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999)",
"outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor,",
"5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9",
"= ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time',",
"Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas",
"Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time",
"df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin",
"print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\")",
"%H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status']",
"pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv')",
"df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement =",
"= df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID =",
"template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac,",
"# specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path",
"pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status']",
"df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature']",
"os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4",
"pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv')",
"= pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] =",
"= 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] =",
"'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 #",
"df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv')",
"data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID']",
"%H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int) template_hvac['Heating_Status'] = template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int)",
"'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num = pd.read_csv(template_path",
"data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/'",
"= template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save",
"'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID']",
"= pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 =",
"pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv')",
"df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2,",
"pd import numpy as np import os # specify the path data_path =",
"df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time =",
"pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv')",
"pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv')",
"tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time']",
"= 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID'] =",
"'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols",
"'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns =",
"= pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 =",
"# check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] =",
"df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] = 11 df_12['Room_ID']",
"into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac",
"yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature',",
"['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied',",
"template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv', index=False) template_hvac.to_csv(save_path +",
"= pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] =",
"= ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1",
"df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID']",
"tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] =",
"= pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 =",
"= 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3,",
"pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999)",
"outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status',",
"df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID']",
"= 1 # check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types",
"df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12",
"pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv')",
"16 df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10,",
"0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time',",
"template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data",
"template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int)",
"specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path =",
"df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin",
"# change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d",
"template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) #",
"= 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] =",
"template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 =",
"= pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path +",
"df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed']",
"pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv')",
"df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID']",
"Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH']",
"= 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path",
"pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9 = pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv')",
"df_13 = pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID']",
"import pandas as pd import numpy as np import os # specify the",
"= 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] =",
"# occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df",
"= template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv', index=False) template_hvac.to_csv(save_path + 'HVAC_Measurement.csv', index=False)",
"tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999)",
"'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2",
"= Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True)",
"= template_hvac['Heating_Status'].astype(int) template_hvac['Cooling_Status'] = template_hvac['Cooling_Status'].astype(int) template_hvac['Building_ID'] = template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] =",
"= pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID']",
"= df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in",
"pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check data print(template_outdoor.isnull().sum())",
"pandas as pd import numpy as np import os # specify the path",
"tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv',",
"= pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14 =",
"tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID']",
"np import os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan",
"'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1",
"3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7",
"'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState',",
"= df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols",
"['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID']",
"pd.read_csv('41.csv') df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv')",
"'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] =",
"= df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 =",
"Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1",
"occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df =",
"Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv')",
"tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999)",
"= df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed =",
"# pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 =",
"path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database",
"pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4",
"df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection']",
"<filename>Phase_1/O-18-by-Yuewei.py import pandas as pd import numpy as np import os # specify",
"pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv')",
"tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan",
"df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin",
"10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14",
"tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed']",
"= pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] =",
"pd.read_csv('KB3.csv') df_14 = pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1",
"df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID']",
"['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns",
"df_12, df_13, df_14, df_15, df_16], ignore_index=True) Date_Time = df['Unnamed: 0'] Occupancy_Measurement = df['Occupied']",
"df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID']",
"template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path",
"added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity',",
"14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3, df_4,",
"df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID']",
"df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11,",
"''' yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time',",
"df_10 = pd.read_csv('43.csv') df_11 = pd.read_csv('KB1.csv') df_12 = pd.read_csv('KB2.csv') df_13 = pd.read_csv('KB3.csv') df_14",
"tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] =",
"1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5",
"print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'],",
"'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time',",
"= Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 =",
"check data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'],",
"tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement']",
"indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection',",
"pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 =",
"= df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time'] = Date_Time tem_1['Indoor_Temp'] =",
"tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999)",
"tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) #",
"= pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 =",
"'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] =",
"as np import os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data",
"= Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999)",
"df_16['Room_ID'] = 16 df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8,",
"pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv')",
"2 df_3['Room_ID'] = 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6",
"pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3",
"df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID']",
"index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] =",
"tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df",
"['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True)",
"df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14,",
"(6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/'",
"'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path =",
"= 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read",
"12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15 df_16['Room_ID'] = 16",
"tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2",
"+ 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path)",
"= pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 =",
"= Date_Time tem_1['Indoor_Temp'] = Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] =",
"template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd",
"'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns",
"'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' # read templates",
"pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv') df_2 = pd.read_csv('20.csv') df_3",
"index=False, header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols",
"template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID'] = 1 template_hvac['HVAC_Zone_ID'] = 1 # check",
"= template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv', index=False) template_hvac.to_csv(save_path",
"RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999)",
"df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] = 2 df_3['Room_ID'] = 3 df_4['Room_ID']",
"RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1",
"= 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10 df_11['Room_ID'] =",
"= Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True) tem_2 =",
"Wind_Direction = df['OutdoorWindDirection'] Wind_Speed = df['OutdoorWindSpeed'] Room_ID = df['Room_ID'] tem_1 = pd.read_csv('Indoor_Measurement.csv') tem_1['Date_Time']",
"import numpy as np import os # specify the path data_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex",
"outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols =",
"df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7",
"+ 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1 = pd.read_csv('19.csv')",
"'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] #",
"template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns",
"Gao/CornishCollege_CleanEXPORT (6)/' template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan",
"11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] = 14 df_15['Room_ID'] = 15",
"Collection/O-18-Nan Gao/_yapan_processing/' # read templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor",
"format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] = template_outdoor['Room_ID'].astype(int)",
"= ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed',",
"df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac = pd.concat([template_hvac, hvac_df], ignore_index=True) template_hvac['Building_ID']",
"Tin tem_1['Indoor_RH'] = RHin tem_1['Indoor_CO2'] = CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999)",
"1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac =",
"as pd import numpy as np import os # specify the path data_path",
"tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False, header=True) ''' yapan added ''' df = df.rename(columns={'Unnamed: 0': 'Date_Time'})",
"'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID']",
"'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1",
"= 10 df_11['Room_ID'] = 11 df_12['Room_ID'] = 12 df_13['Room_ID'] = 13 df_14['Room_ID'] =",
"template_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/OB Database Consolidation/Templates/' save_path = 'D:/yapan_office_D/Data/Annex-79-OB-Database/2021-06-03-raw-data/Annex 79 Data Collection/O-18-Nan Gao/_yapan_processing/' #",
"Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv',",
"df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15, df_16], ignore_index=True)",
"= df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor",
"pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_hvac['Date_Time'] = pd.to_datetime(template_hvac['Date_Time'], format=\"%Y-%m-%d %H:%M:%S\") template_outdoor['Building_ID'] = template_outdoor['Building_ID'].astype(int) template_outdoor['Room_ID'] =",
"header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID",
"df['Unnamed: 0'] Occupancy_Measurement = df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in =",
"df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation', 'Room_ID'] template_outdoor =",
"'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time',",
"template_hvac['Building_ID'].astype(int) template_hvac['Room_ID'] = template_hvac['Room_ID'].astype(int) template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv',",
"= 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] = 7 df_8['Room_ID'] =",
"templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path + 'Outdoor_Measurement.csv')",
"data print(template_outdoor.isnull().sum()) print(template_outdoor.dtypes) print(template_hvac.isnull().sum()) print(template_hvac.dtypes) # change data types template_outdoor['Date_Time'] = pd.to_datetime(template_outdoor['Date_Time'], format=\"%Y-%m-%d",
"read templates into pandas template_occ_num = pd.read_csv(template_path + 'Occupant_Number_Measurement.csv') template_outdoor = pd.read_csv(template_path +",
"'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH', 'Wind_Direction', 'Wind_Speed', 'Precipitation', 'Solar_Radiation',",
"tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3 = pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout",
"= pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns =",
"= ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp', 'Outdoor_RH',",
"6 df_7['Room_ID'] = 7 df_8['Room_ID'] = 8 df_9['Room_ID'] = 9 df_10['Room_ID'] = 10",
"= 16 df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9,",
"= pd.read_csv('Outdoor_Measurement.csv') tem_3['Date_Time'] = Date_Time tem_3['Outdoor_Temp'] = Tout tem_3['Outdoor_RH'] = RHout tem_3['Wind_Speed'] =",
"tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] = Room_ID tem_2['Date_Time'].fillna(-999) tem_2['Room_ID'].fillna(-999) tem_2['Occupancy_Measurement'].fillna(-999) tem_2.to_csv('Occupancy_Measurement_18.csv', index=False, header=True) tem_3",
"index=False, header=True) tem_2 = pd.read_csv('Occupancy_Measurement.csv') tem_2['Date_Time'] = Date_Time tem_2['Occupancy_Measurement'] = Occupancy_Measurement tem_2['Room_ID'] =",
"df = df.rename(columns={'Unnamed: 0': 'Date_Time'}) # indoor_cols = ['Date_Time', 'IndoorTemperature', 'IndoorHumidity', 'IndoorCO2', 'Room_ID']",
"'Room_ID'] template_outdoor = pd.concat([template_outdoor, outdoor_df], ignore_index=True) template_outdoor['Building_ID'] = 1 template_hvac.columns hvac_df = df[hvac_cols]",
"= df['Occupied'] Tin = df['IndoorTemperature'] RHin = df['IndoorHumidity'] CO2in = df['IndoorCO2'] Tout =",
"tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999) tem_3['Outdoor_RH'].fillna(-999) tem_3['Wind_Speed'].fillna(-999) tem_3['Wind_Direction'].fillna(-999) tem_3.to_csv('Outdoor_Measurement_18.csv', index=False,",
"= pd.read_csv('KB4.csv') df_15 = pd.read_csv('KB5.csv') df_16 = pd.read_csv('KB6.csv') df_1['Room_ID'] = 1 df_2['Room_ID'] =",
"CO2in tem_1['Room_ID'] = Room_ID tem_1['Date_Time'].fillna(-999) tem_1['Date_Time'].fillna(-999) tem_1['Indoor_Temp'].fillna(-999) tem_1['Indoor_RH'].fillna(-999) tem_1['Indoor_CO2'].fillna(-999) tem_1['Room_ID'].fillna(-999) tem_1.to_csv('Indoor_Measurement_18.csv', index=False, header=True)",
"'Precipitation', 'SolarRadiation', 'Room_ID'] # occ_cols = ['Date_Time', 'Occupied', 'Room_ID'] hvac_cols = ['Date_Time', 'HeatingState',",
"= pd.read_csv(template_path + 'Outdoor_Measurement.csv') template_hvac = pd.read_csv(template_path + 'HVAC_Measurement.csv') os.chdir(data_path) # pwd df_1",
"= 3 df_4['Room_ID'] = 4 df_5['Room_ID'] = 5 df_6['Room_ID'] = 6 df_7['Room_ID'] =",
"df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8 = pd.read_csv('40.csv') df_9",
"hvac_cols = ['Date_Time', 'HeatingState', 'CoolingState', 'Room_ID'] outdoor_df = df[outdoor_cols] outdoor_df.columns = ['Date_Time', 'Outdoor_Temp',",
"= 1 template_hvac.columns hvac_df = df[hvac_cols] hvac_df.columns = ['Date_Time', 'Heating_Status', 'Cooling_Status', 'Room_ID'] template_hvac",
"CO2in = df['IndoorCO2'] Tout = df['OutdoorTemperature'] RHout = df['OutdoorHumidity'] Wind_Direction = df['OutdoorWindDirection'] Wind_Speed",
"= RHout tem_3['Wind_Speed'] = Wind_Speed tem_3['Wind_Direction'] = Wind_Direction tem_3['Building_ID'] = 1 tem_3['Date_Time'].fillna(-999) tem_3['Outdoor_Temp'].fillna(-999)",
"df_2 = pd.read_csv('20.csv') df_3 = pd.read_csv('27.csv') df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6",
"df_4 = pd.read_csv('28.csv') df_5 = pd.read_csv('29.csv') df_6 = pd.read_csv('30.csv') df_7 = pd.read_csv('31.csv') df_8",
"template_hvac['HVAC_Zone_ID'] = template_hvac['HVAC_Zone_ID'].astype(int) # save data template_outdoor.to_csv(save_path + 'Outdoor_Measurement.csv', index=False) template_hvac.to_csv(save_path + 'HVAC_Measurement.csv',",
"'IndoorHumidity', 'IndoorCO2', 'Room_ID'] outdoor_cols = ['Date_Time', 'OutdoorTemperature', 'OutdoorHumidity', 'OutdoorWindDirection', 'OutdoorWindSpeed', 'Precipitation', 'SolarRadiation', 'Room_ID']"
] |
[
"25 times per second.\", \"(23) When a family cat died in ancient Egypt,",
"Dogs make only about 10.\", \"(7) Every year, nearly four million cats are",
"cat can travel at a top speed of approximately 31 mph (49 km)",
"ancient that its name is the Egyptian word for “cat.”\", \"(41) The first",
"ancient Egypt, family members would mourn by shaving off their eyebrows. They also",
"\"Oh, and remember, next Friday is Swedish luggage day, so, you know, if",
"over 65 feet (20 meters), due largely to their “righting reflex.” The eyes",
"Wonderland. With the ability to disappear, this mysterious character embodies the magic and",
"cats do not have a sweet tooth. Scientists believe this is due to",
"direct sounds into the ear, and insulate the ears are called “ear furnishings.”\",",
"land on its feet. Even cats without a tail have this ability.\", \"(36)",
"stuff them into sacks and toss the cats into bonfires. On holy days,",
"a sculpted wooden mask and the tiny mummy was placed in the family",
"emerged around 12 million years ago.\", \"(28) The biggest wildcat today is the",
"cats, which can weigh 25 lbs (11.3 kg), or nearly twice as much",
"with cat (catt, cath, chat, katze) stem from the Latin catus, meaning domestic",
"in space so the cat can land on its feet. Even cats without",
"a sweet tooth. Scientists believe this is due to a mutation in a",
"of mice.\", \"(24) In 1888, more than 300,000 mummified cats were found an",
"and other important cities.\", \"(27) The earliest ancestor of the modern cat lived",
"appears red to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first wife, Lilith,",
"is to a dog’s. Both humans and cats have identical regions in their",
"out dirt direct sounds into the ear, and insulate the ears are called",
"similar to a human brain than it is to a dog’s. Both humans",
"do not have a sweet tooth. Scientists believe this is due to a",
"\"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words with multiple random responses",
"neighborhood in Baghdad, Iraq. Tabbies got their name because their striped coats resembled",
"sold to rich people in Athens and other important cities.\", \"(27) The earliest",
"mph (49 km) over a short distance.\", \"(21) A cat rubs against people",
"recognized breeds.\", \"(9) Approximately 24 cat skins can make a coat.\", \"(10) While",
"babies. This may be the root of the superstition that a cat will",
"group of cats is called a “clowder”.\", \"(5) A cat can’t climb head",
"pack for the back.\", \"I like turtles.\", \"I like pie.\", \"Das ist ein",
"as an average cat weighs.\", \"(35) Some cats have survived falls of over",
"means a nine-year-old cat has been awake for only three years of its",
"in a cat’s ear that help keep out dirt direct sounds into the",
"island of Cyprus. This grave predates early Egyptian art depicting cats by 4,000",
"cat’s paw points the same way. To get down from a tree, a",
"punishable by death. Phoenician traders eventually succeeded in smuggling felines, which they sold",
"be associated with the connotation of a cat being soft, warm, and fuzzy.\",",
"explosion of the rat population, which exacerbated the effects of the Black Death.\",",
"# dictionary of trigger words with single 1:1 reply singlereplydict = { \"tableflip\":",
"A cat can’t climb head first down a tree because every claw on",
"secondary words in Lithuanian (puz) and Low German puus. Some scholars suggest that",
"on each side of its face.\", \"(43) A cat’s eyesight is both better",
"popular pets: there are 73 million cats compared to 63 million dogs. Over",
"In 1963, France blasted the cat into outer space. Electrodes implanted in her",
"# dictionary of trigger words with multiple random responses multireplydict = { \"backpack\":",
"trip.\", \"(14) The group of words associated with cat (catt, cath, chat, katze)",
"with multiple random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm...",
"on the ark from being eaten by rats. In reply, God made the",
"striped coats resembled the famous wavy patterns in the silk produced in this",
"breasts. The cat was embalmed with a sculpted wooden mask and the tiny",
"other important cities.\", \"(27) The earliest ancestor of the modern cat lived about",
"be more than 12 feet (3.6 m) long (about the size of a",
"cats are eaten in Asia.\", \"(8) There are more than 500 million domestic",
"found an Egyptian cemetery. They were stripped of their wrappings and carted off",
"is in space so the cat can land on its feet. Even cats",
"\"(48) In the original Italian version of Cinderella, the benevolent fairy godmother figure",
"kittens, of which 15 survived.\", \"(26) Smuggling a cat out of ancient Egypt",
"4,000 years or more.\", \"(11) During the time of the Spanish Inquisition, Pope",
"It’s worse because they don’t see color as well as humans do. Scientists",
"dog’s. Both humans and cats have identical regions in their brains that are",
"see in much dimmer light and they have a wider peripheral view. It’s",
"falls of over 65 feet (20 meters), due largely to their “righting reflex.”",
"folds deep in the throat. To do this, a muscle in the larynx",
"Tabbies got their name because their striped coats resembled the famous wavy patterns",
"only three years of its life.\", \"(48) In the original Italian version of",
"Dogs and humans bob their heads up and down.\", \"(3) The technical term",
"25 lbs (11.3 kg), or nearly twice as much as an average cat",
"it keeps its head level. Dogs and humans bob their heads up and",
"as evil and thousands of cats were burned. Unfortunately, the widespread killing of",
"cat’s brain is biologically more similar to a human brain than it is",
"Lewis Carroll’s Alice in Wonderland. With the ability to disappear, this mysterious character",
"has a unique texture that makes it water resistant.\", \"(40) The Egyptian Mau",
"ago.\", \"(28) The biggest wildcat today is the Siberian Tiger. It can be",
"hairball is a “bezoar”.\", \"(4) A group of cats is called a “clowder”.\",",
"into sacks and toss the cats into bonfires. On holy days, people celebrated",
"breed is so ancient that its name is the Egyptian word for “cat.”\",",
"tell it where it is in space so the cat can land on",
"that act as compasses.\", ], } def webhook(request): if request.method == \"POST\": update",
"multiple random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah...",
"in her brains sent neurological signals back to Earth. She survived the trip.\",",
"the modern cat lived about 30 million years ago. Scientists called it the",
"Maine Coon cat and the Siamese cat.\", \"(34) The smallest pedigreed cat is",
"The cat was embalmed with a sculpted wooden mask and the tiny mummy",
"sneeze, and out popped a cat.\", \"(19) A cat’s hearing is better than",
"Approximately 24 cat skins can make a coat.\", \"(10) While it is commonly",
"into the ear, and insulate the ears are called “ear furnishings.”\", \"(50) The",
"the right eye and the nerves from the right side of the brain",
"could be imitative of the hissing sound used to get a cat’s attention.",
"a tail have this ability.\", \"(36) Some Siamese cats appear cross-eyed because the",
"cats.\", \"(46) The smallest wildcat today is the Black-footed cat. The females are",
"# these responses have several options to be selected at random for trigger",
"their “righting reflex.” The eyes and balance organs in the inner ear tell",
"telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped responses",
"of their wrappings and carted off to be used by farmers in England",
"Proailurus, which means “first cat” in Greek. The group of animals that pet",
"try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass",
"to 700 pounds (317 kg).\", \"(29) A cat’s brain is biologically more similar",
"pet was a cat named “<NAME>”. He cost his owner $50,000, making him",
"\"🎶🐙🎶\", } # dictionary of trigger words with multiple random responses multireplydict =",
"cm) long and can weigh as little as 2.5 lbs (1.2 kg).\", \"(47)",
"five large cans of cat food. The largest pedigreed cats are Maine Coon",
"Europe and North America consider the black cat a sign of bad luck,",
"could be associated with the connotation of a cat being soft, warm, and",
"\"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words with",
"Egyptian cemetery. They were stripped of their wrappings and carted off to be",
"slang word for the female pudenda, it could be associated with the connotation",
"that pet cats belong to emerged around 12 million years ago.\", \"(28) The",
"this mysterious character embodies the magic and sorcery historically associated with cats.\", \"(46)",
"\"(44) Spanish-Jewish folklore recounts that Adam’s first wife, Lilith, became a black vampire",
"The group of words associated with cat (catt, cath, chat, katze) stem from",
"They also held elaborate funerals during which they drank wine and beat their",
"of their heads because Mohammad would often rest his hand on the cat’s",
"cat. In fact, the breed is so ancient that its name is the",
"to a litter of between one and nine kittens. The largest known litter",
"from the Latin catus, meaning domestic cat, as opposed to feles, or wild",
"modern cat lived about 30 million years ago. Scientists called it the Proailurus,",
"can land on its feet. Even cats without a tail have this ability.\",",
"down a tree because every claw on a cat’s paw points the same",
"tree, a cat must back down.\", \"(6) Cats make about 100 different sounds.",
"with the connotation of a cat being soft, warm, and fuzzy.\", \"(16) Approximately",
"pet cat was recently found in a 9,500-year-old grave on the Mediterranean island",
"of hair in a cat’s ear that help keep out dirt direct sounds",
"back down.\", \"(6) Cats make about 100 different sounds. Dogs make only about",
"root of secondary words in Lithuanian (puz) and Low German puus. Some scholars",
"their name because their striped coats resembled the famous wavy patterns in the",
"73 million cats compared to 63 million dogs. Over 30% of households in",
"superstition that a cat will smother a sleeping baby or suck out the",
"his favorite cat, Muezza, was a tabby. Legend says that tabby cats have",
"\"(36) Some Siamese cats appear cross-eyed because the nerves from the left side",
"with scent glands around its face. The tail area and paws also carry",
"to, go ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\",",
"scent.\", \"(22) Researchers are unsure exactly how a cat purrs. Most veterinarians believe",
"request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text",
"km) over a short distance.\", \"(21) A cat rubs against people not only",
"light and they have a wider peripheral view. It’s worse because they don’t",
"little tufts of hair in a cat’s ear that help keep out dirt",
"the air passage about 25 times per second.\", \"(23) When a family cat",
"of a small car) and weigh up to 700 pounds (317 kg).\", \"(29)",
"rucksack auf Deutsch!\", \"Oh, and remember, next Friday is Swedish luggage day, so,",
"Coon cat and the Siamese cat.\", \"(34) The smallest pedigreed cat is a",
"three years of its life.\", \"(48) In the original Italian version of Cinderella,",
"\"(22) Researchers are unsure exactly how a cat purrs. Most veterinarians believe that",
"luck, in Britain and Australia, black cats are considered lucky.\", \"(33) The most",
"weighs.\", \"(35) Some cats have survived falls of over 65 feet (20 meters),",
"cat rubs against people not only to be affectionate but also to mark",
"On holy days, people celebrated by tossing cats from church towers.\", \"(13) The",
"balance organs in the inner ear tell it where it is in space",
"paw points the same way. To get down from a tree, a cat",
"large cans of cat food. The largest pedigreed cats are Maine Coon cats,",
"Felicette (a.k.a. “Astrocat”) In 1963, France blasted the cat into outer space. Electrodes",
"\"(45) Perhaps the most famous comic cat is the Cheshire Cat in Lewis",
"version of Cinderella, the benevolent fairy godmother figure was a cat.\", \"(49) The",
"a cat will smother a sleeping baby or suck out the child’s breath.\",",
"her brains sent neurological signals back to Earth. She survived the trip.\", \"(14)",
"to God for help protecting all the food he stored on the ark",
"North America consider the black cat a sign of bad luck, in Britain",
"says that tabby cats have an “M” for Mohammed on top of their",
"¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words",
"the sunlight to find their way or that cats have magnetized cells in",
"ist ein rucksack auf Deutsch!\", \"Oh, and remember, next Friday is Swedish luggage",
"\"(4) A group of cats is called a “clowder”.\", \"(5) A cat can’t",
"cats led to an explosion of the rat population, which exacerbated the effects",
"“first cat” in Greek. The group of animals that pet cats belong to",
"catus, meaning domestic cat, as opposed to feles, or wild cat.\", \"(15) The",
"which exacerbated the effects of the Black Death.\", \"(12) During the Middle Ages,",
"was a cat.\", \"(49) The little tufts of hair in a cat’s ear",
"name is the Egyptian word for “cat.”\", \"(41) The first commercially cloned pet",
"\"(32) While many parts of Europe and North America consider the black cat",
"\"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words with multiple random responses multireplydict",
"Bast, who had a woman’s body and a cat’s head.\", \"(31) Mohammed loved",
"It can be more than 12 feet (3.6 m) long (about the size",
"between one and nine kittens. The largest known litter ever produced was 19",
"“puss” is the root of the principal word for “cat” in the Romanian",
"this ability.\", \"(36) Some Siamese cats appear cross-eyed because the nerves from the",
"To do this, a muscle in the larynx opens and closes the air",
"sound used to get a cat’s attention. As a slang word for the",
"the U.S. annually.\", \"(17) Cats are North America’s most popular pets: there are",
"cities.\", \"(27) The earliest ancestor of the modern cat lived about 30 million",
"in multireplydict: try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext) except",
"In reply, God made the lion sneeze, and out popped a cat.\", \"(19)",
"there are 73 million cats compared to 63 million dogs. Over 30% of",
"their way or that cats have magnetized cells in their brains that act",
"connotation of a cat being soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people",
"height in a single bound.\", \"(39) Cats hate the water because their fur",
"associated with withcraft, and on St. John’s Day, people all over Europe would",
"on the cat’s head.\", \"(32) While many parts of Europe and North America",
"survived.\", \"(26) Smuggling a cat out of ancient Egypt was punishable by death.",
"\"(20) A cat can travel at a top speed of approximately 31 mph",
"top speed of approximately 31 mph (49 km) over a short distance.\", \"(21)",
"and North America consider the black cat a sign of bad luck, in",
"figure was a cat.\", \"(49) The little tufts of hair in a cat’s",
"cats were burned. Unfortunately, the widespread killing of cats led to an explosion",
"random for trigger in multireplydict: try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger])",
"a cat purrs. Most veterinarians believe that a cat purrs by vibrating vocal",
"unsure exactly how a cat purrs. Most veterinarians believe that a cat purrs",
"be selected at random for trigger in multireplydict: try: if trigger in messagetext.lower():",
"single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\":",
"are less than 20 inches (50 cm) long and can weigh as little",
"popped a cat.\", \"(19) A cat’s hearing is better than a dog’s. And",
"for only three years of its life.\", \"(48) In the original Italian version",
"singlereplydict: try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError:",
"weigh up to 700 pounds (317 kg).\", \"(29) A cat’s brain is biologically",
"people are bitten by cats in the U.S. annually.\", \"(17) Cats are North",
"is the Siberian Tiger. It can be more than 12 feet (3.6 m)",
"Muezza, was a tabby. Legend says that tabby cats have an “M” for",
"cat’s scent.\", \"(22) Researchers are unsure exactly how a cat purrs. Most veterinarians",
"thousands of cats were burned. Unfortunately, the widespread killing of cats led to",
"sent neurological signals back to Earth. She survived the trip.\", \"(14) The group",
"a mutation in a key taste receptor.\", \"(2) When a cat chases its",
"have survived falls of over 65 feet (20 meters), due largely to their",
"can make a coat.\", \"(10) While it is commonly thought that the ancient",
"of a cat being soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people are",
"Coon cats, which can weigh 25 lbs (11.3 kg), or nearly twice as",
"term for a cat’s hairball is a “bezoar”.\", \"(4) A group of cats",
"annually.\", \"(17) Cats are North America’s most popular pets: there are 73 million",
"a nine-year-old cat has been awake for only three years of its life.\",",
"all over Europe would stuff them into sacks and toss the cats into",
"which the cat tries to correct by “crossing” its eyes.\", \"(37) Researchers believe",
"🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"(",
"sculpted wooden mask and the tiny mummy was placed in the family tomb",
"German puus. Some scholars suggest that “puss” could be imitative of the hissing",
"[ \"(1) Unlike dogs, cats do not have a sweet tooth. Scientists believe",
"way. To get down from a tree, a cat must back down.\", \"(6)",
"biggest wildcat today is the Siberian Tiger. It can be more than 12",
"believe the word “tabby” comes from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies",
"\"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\", \"I like turtles.\", \"I",
"space. Electrodes implanted in her brains sent neurological signals back to Earth. She",
"by rats. In reply, God made the lion sneeze, and out popped a",
"year, nearly four million cats are eaten in Asia.\", \"(8) There are more",
"The smallest pedigreed cat is a Singapura, which can weigh just 4 lbs",
"domestic cat, as opposed to feles, or wild cat.\", \"(15) The term “puss”",
"be imitative of the hissing sound used to get a cat’s attention. As",
"its head level. Dogs and humans bob their heads up and down.\", \"(3)",
"to two octaves higher than a human.\", \"(20) A cat can travel at",
"words in Lithuanian (puz) and Low German puus. Some scholars suggest that “puss”",
"and the root of secondary words in Lithuanian (puz) and Low German puus.",
"Latin catus, meaning domestic cat, as opposed to feles, or wild cat.\", \"(15)",
"Adam’s first wife, Lilith, became a black vampire cat, sucking the blood from",
"death. Phoenician traders eventually succeeded in smuggling felines, which they sold to rich",
"of the brain go to mostly the right eye and the nerves from",
"a cat’s ear that help keep out dirt direct sounds into the ear,",
"more than 300,000 mummified cats were found an Egyptian cemetery. They were stripped",
"as 2.5 lbs (1.2 kg).\", \"(47) On average, cats spend 2/3 of every",
"eventually succeeded in smuggling felines, which they sold to rich people in Athens",
"nerves from the left side of the brain go to mostly the right",
"next Friday is Swedish luggage day, so, you know, if you want to,",
"cat’s ear that help keep out dirt direct sounds into the ear, and",
"the ability to disappear, this mysterious character embodies the magic and sorcery historically",
"The term “puss” is the root of the principal word for “cat” in",
"cats as evil and thousands of cats were burned. Unfortunately, the widespread killing",
"the magic and sorcery historically associated with cats.\", \"(46) The smallest wildcat today",
"name because their striped coats resembled the famous wavy patterns in the silk",
"John’s Day, people all over Europe would stuff them into sacks and toss",
"300,000 mummified cats were found an Egyptian cemetery. They were stripped of their",
"\"(13) The first cat in space was a French cat named Felicette (a.k.a.",
"2/3 of every day sleeping. That means a nine-year-old cat has been awake",
"its territory with scent glands around its face. The tail area and paws",
"Experts think cats either use the angle of the sunlight to find their",
"of secondary words in Lithuanian (puz) and Low German puus. Some scholars suggest",
"as well as humans do. Scientists believe grass appears red to cats.\", \"(44)",
"\"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of",
"cats by 4,000 years or more.\", \"(11) During the time of the Spanish",
"predates early Egyptian art depicting cats by 4,000 years or more.\", \"(11) During",
"Electrodes implanted in her brains sent neurological signals back to Earth. She survived",
"pet cats belong to emerged around 12 million years ago.\", \"(28) The biggest",
"a human.\", \"(20) A cat can travel at a top speed of approximately",
"Scientists called it the Proailurus, which means “first cat” in Greek. The group",
"can be more than 12 feet (3.6 m) long (about the size of",
"he stored on the ark from being eaten by rats. In reply, God",
"evil and thousands of cats were burned. Unfortunately, the widespread killing of cats",
"and beat their breasts. The cat was embalmed with a sculpted wooden mask",
"the same way. To get down from a tree, a cat must back",
"pedigreed cats are Maine Coon cats, which can weigh 25 lbs (11.3 kg),",
"time of the Spanish Inquisition, Pope Innocent VIII condemned cats as evil and",
"\"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\":",
"with a sculpted wooden mask and the tiny mummy was placed in the",
"\"(24) In 1888, more than 300,000 mummified cats were found an Egyptian cemetery.",
"and humans bob their heads up and down.\", \"(3) The technical term for",
"wooden mask and the tiny mummy was placed in the family tomb or",
"cat’s hearing is better than a dog’s. And a cat can hear high-frequency",
"Egyptian art depicting cats by 4,000 years or more.\", \"(11) During the time",
"the effects of the Black Death.\", \"(12) During the Middle Ages, cats were",
"traders eventually succeeded in smuggling felines, which they sold to rich people in",
"cat is the Persian cat, followed by the Maine Coon cat and the",
"nearly four million cats are eaten in Asia.\", \"(8) There are more than",
"bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single 1:1 reply singlereplydict",
"or more.\", \"(11) During the time of the Spanish Inquisition, Pope Innocent VIII",
"hear high-frequency sounds up to two octaves higher than a human.\", \"(20) A",
"off their eyebrows. They also held elaborate funerals during which they drank wine",
"30 million years ago. Scientists called it the Proailurus, which means “first cat”",
"of over 65 feet (20 meters), due largely to their “righting reflex.” The",
"cats either use the angle of the sunlight to find their way or",
"bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses have several options to be",
"a sleeping baby or suck out the child’s breath.\", \"(45) Perhaps the most",
"more than 12 feet (3.6 m) long (about the size of a small",
"ability to disappear, this mysterious character embodies the magic and sorcery historically associated",
"chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped responses for trigger",
"keep out dirt direct sounds into the ear, and insulate the ears are",
"in the family tomb or in a pet cemetery with tiny mummies of",
"\"(3) The technical term for a cat’s hairball is a “bezoar”.\", \"(4) A",
"and thousands of cats were burned. Unfortunately, the widespread killing of cats led",
"of its face.\", \"(43) A cat’s eyesight is both better and worse than",
"\"(7) Every year, nearly four million cats are eaten in Asia.\", \"(8) There",
"mask and the tiny mummy was placed in the family tomb or in",
"car) and weigh up to 700 pounds (317 kg).\", \"(29) A cat’s brain",
"and carted off to be used by farmers in England and the U.S.",
"and worse than humans. It is better because cats can see in much",
"years ago. Scientists called it the Proailurus, which means “first cat” in Greek.",
"cats in the world, with approximately 40 recognized breeds.\", \"(9) Approximately 24 cat",
"by “crossing” its eyes.\", \"(37) Researchers believe the word “tabby” comes from Attabiyah,",
"do. Scientists believe grass appears red to cats.\", \"(44) Spanish-Jewish folklore recounts that",
"mostly the right eye and the nerves from the right side of the",
"cats appear cross-eyed because the nerves from the left side of the brain",
"a slang word for the female pudenda, it could be associated with the",
"cells in their brains that act as compasses.\", ], } def webhook(request): if",
"cat food. The largest pedigreed cats are Maine Coon cats, which can weigh",
"24 cat skins can make a coat.\", \"(10) While it is commonly thought",
"don’t see color as well as humans do. Scientists believe grass appears red",
"its face. The tail area and paws also carry the cat’s scent.\", \"(22)",
"wet. The Turkish Van, however, is one cat that likes swimming. Bred in",
"where it is in space so the cat can land on its feet.",
"(puz) and Low German puus. Some scholars suggest that “puss” could be imitative",
"times its own height in a single bound.\", \"(39) Cats hate the water",
"the angle of the sunlight to find their way or that cats have",
"the cat’s head.\", \"(32) While many parts of Europe and North America consider",
"and paws also carry the cat’s scent.\", \"(22) Researchers are unsure exactly how",
"A cat usually has about 12 whiskers on each side of its face.\",",
"the brain go mostly to the left eye. This causes some double vision,",
"Scientists believe this is due to a mutation in a key taste receptor.\",",
"in central Asia, its coat has a unique texture that makes it water",
"cat named “<NAME>”. He cost his owner $50,000, making him one of the",
"commonly thought that the ancient Egyptians were the first to domesticate cats, the",
"the silk produced in this city.\", \"(38) A cat can jump up to",
"get a cat’s attention. As a slang word for the female pudenda, it",
"it is in space so the cat can land on its feet. Even",
"12 feet (3.6 m) long (about the size of a small car) and",
"of between one and nine kittens. The largest known litter ever produced was",
"compasses.\", ], } def webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot)",
"a muscle in the larynx opens and closes the air passage about 25",
"trigger in multireplydict: try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext)",
"average, cats spend 2/3 of every day sleeping. That means a nine-year-old cat",
"cat.\", \"(15) The term “puss” is the root of the principal word for",
"as humans do. Scientists believe grass appears red to cats.\", \"(44) Spanish-Jewish folklore",
"about 25 times per second.\", \"(23) When a family cat died in ancient",
"\"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵",
"\"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\",",
"of bad luck, in Britain and Australia, black cats are considered lucky.\", \"(33)",
"better and worse than humans. It is better because cats can see in",
"family cat died in ancient Egypt, family members would mourn by shaving off",
"cans of cat food. The largest pedigreed cats are Maine Coon cats, which",
"embalmed with a sculpted wooden mask and the tiny mummy was placed in",
"succeeded in smuggling felines, which they sold to rich people in Athens and",
"a black vampire cat, sucking the blood from sleeping babies. This may be",
"than 20 inches (50 cm) long and can weigh as little as 2.5",
"better because cats can see in much dimmer light and they have a",
"\"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do not",
"# source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do not have a",
"well when it’s wet. The Turkish Van, however, is one cat that likes",
"their heads because Mohammad would often rest his hand on the cat’s head.\",",
"katze) stem from the Latin catus, meaning domestic cat, as opposed to feles,",
"is both better and worse than humans. It is better because cats can",
"or nearly twice as much as an average cat weighs.\", \"(35) Some cats",
"silk produced in this city.\", \"(38) A cat can jump up to five",
"mark out its territory with scent glands around its face. The tail area",
"A cat rubs against people not only to be affectionate but also to",
"veterinarians believe that a cat purrs by vibrating vocal folds deep in the",
"tree because every claw on a cat’s paw points the same way. To",
"have a wider peripheral view. It’s worse because they don’t see color as",
"it is to a dog’s. Both humans and cats have identical regions in",
"cat, as opposed to feles, or wild cat.\", \"(15) The term “puss” is",
"have a sweet tooth. Scientists believe this is due to a mutation in",
"cats were associated with withcraft, and on St. John’s Day, people all over",
"ein rucksack auf Deutsch!\", \"Oh, and remember, next Friday is Swedish luggage day,",
"or suck out the child’s breath.\", \"(45) Perhaps the most famous comic cat",
"eye. This causes some double vision, which the cat tries to correct by",
"which 15 survived.\", \"(26) Smuggling a cat out of ancient Egypt was punishable",
"in much dimmer light and they have a wider peripheral view. It’s worse",
"condemned cats as evil and thousands of cats were burned. Unfortunately, the widespread",
"cat can jump up to five times its own height in a single",
"space so the cat can land on its feet. Even cats without a",
"birth to a litter of between one and nine kittens. The largest known",
"and closes the air passage about 25 times per second.\", \"(23) When a",
"from being eaten by rats. In reply, God made the lion sneeze, and",
"The first commercially cloned pet was a cat named “<NAME>”. He cost his",
"Egyptian Mau is probably the oldest breed of cat. In fact, the breed",
"options to be selected at random for trigger in multireplydict: try: if trigger",
"approximately 40 recognized breeds.\", \"(9) Approximately 24 cat skins can make a coat.\",",
"\"(39) Cats hate the water because their fur does not insulate well when",
"water resistant.\", \"(40) The Egyptian Mau is probably the oldest breed of cat.",
"the ancient Egyptians were the first to domesticate cats, the oldest known pet",
"A cat’s brain is biologically more similar to a human brain than it",
"nine-year-old cat has been awake for only three years of its life.\", \"(48)",
"cat that likes swimming. Bred in central Asia, its coat has a unique",
"years of its life.\", \"(48) In the original Italian version of Cinderella, the",
"are 73 million cats compared to 63 million dogs. Over 30% of households",
"\"(46) The smallest wildcat today is the Black-footed cat. The females are less",
"(50 cm) long and can weigh as little as 2.5 lbs (1.2 kg).\",",
"brains that act as compasses.\", ], } def webhook(request): if request.method == \"POST\":",
"is due to a mutation in a key taste receptor.\", \"(2) When a",
"on its feet. Even cats without a tail have this ability.\", \"(36) Some",
"second.\", \"(23) When a family cat died in ancient Egypt, family members would",
"regions in their brains that are responsible for emotions.\", \"(30) Many Egyptians worshipped",
"\"(30) Many Egyptians worshipped the goddess Bast, who had a woman’s body and",
"the Middle Ages, cats were associated with withcraft, and on St. John’s Day,",
"cat, sucking the blood from sleeping babies. This may be the root of",
"cat chases its prey, it keeps its head level. Dogs and humans bob",
"2.5 lbs (1.2 kg).\", \"(47) On average, cats spend 2/3 of every day",
"not only to be affectionate but also to mark out its territory with",
"is commonly thought that the ancient Egyptians were the first to domesticate cats,",
"technical term for a cat’s hairball is a “bezoar”.\", \"(4) A group of",
"\"(19) A cat’s hearing is better than a dog’s. And a cat can",
"mice.\", \"(24) In 1888, more than 300,000 mummified cats were found an Egyptian",
"space was a French cat named Felicette (a.k.a. “Astrocat”) In 1963, France blasted",
"associated with cat (catt, cath, chat, katze) stem from the Latin catus, meaning",
"the black cat a sign of bad luck, in Britain and Australia, black",
"about five large cans of cat food. The largest pedigreed cats are Maine",
"points the same way. To get down from a tree, a cat must",
"\"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵",
"[ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [",
"cat’s head.\", \"(32) While many parts of Europe and North America consider the",
"pass # these responses have several options to be selected at random for",
"top of their heads because Mohammad would often rest his hand on the",
"to emerged around 12 million years ago.\", \"(28) The biggest wildcat today is",
"and insulate the ears are called “ear furnishings.”\", \"(50) The ability of a",
"heads because Mohammad would often rest his hand on the cat’s head.\", \"(32)",
"and remember, next Friday is Swedish luggage day, so, you know, if you",
"Unlike dogs, cats do not have a sweet tooth. Scientists believe this is",
"cat (catt, cath, chat, katze) stem from the Latin catus, meaning domestic cat,",
"messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses have",
"because their fur does not insulate well when it’s wet. The Turkish Van,",
"pets: there are 73 million cats compared to 63 million dogs. Over 30%",
"reply, God made the lion sneeze, and out popped a cat.\", \"(19) A",
"art depicting cats by 4,000 years or more.\", \"(11) During the time of",
"Lilith, became a black vampire cat, sucking the blood from sleeping babies. This",
"octaves higher than a human.\", \"(20) A cat can travel at a top",
"they sold to rich people in Athens and other important cities.\", \"(27) The",
"the Mediterranean island of Cyprus. This grave predates early Egyptian art depicting cats",
"except AttributeError: pass # these responses have several options to be selected at",
"of animals that pet cats belong to emerged around 12 million years ago.\",",
"1963, France blasted the cat into outer space. Electrodes implanted in her brains",
"\"(6) Cats make about 100 different sounds. Dogs make only about 10.\", \"(7)",
"Innocent VIII condemned cats as evil and thousands of cats were burned. Unfortunately,",
"\"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\":",
"cats have identical regions in their brains that are responsible for emotions.\", \"(30)",
"find its way home is called “psi-traveling.” Experts think cats either use the",
"\"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓",
"key taste receptor.\", \"(2) When a cat chases its prey, it keeps its",
"of households in North America own a cat.\", \"(18) According to Hebrew legend,",
"in the larynx opens and closes the air passage about 25 times per",
"brain go to mostly the right eye and the nerves from the right",
"side of the brain go mostly to the left eye. This causes some",
"largest known litter ever produced was 19 kittens, of which 15 survived.\", \"(26)",
"fuzzy.\", \"(16) Approximately 40,000 people are bitten by cats in the U.S. annually.\",",
"Approximately 40,000 people are bitten by cats in the U.S. annually.\", \"(17) Cats",
"ear tell it where it is in space so the cat can land",
"bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped responses for",
"cat purrs by vibrating vocal folds deep in the throat. To do this,",
"some double vision, which the cat tries to correct by “crossing” its eyes.\",",
"ago. Scientists called it the Proailurus, which means “first cat” in Greek. The",
"as compasses.\", ], } def webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True),",
"cat, followed by the Maine Coon cat and the Siamese cat.\", \"(34) The",
"less than 20 inches (50 cm) long and can weigh as little as",
"cat can’t climb head first down a tree because every claw on a",
"1888, more than 300,000 mummified cats were found an Egyptian cemetery. They were",
"cat.\", \"(19) A cat’s hearing is better than a dog’s. And a cat",
"hearing is better than a dog’s. And a cat can hear high-frequency sounds",
"popular pedigreed cat is the Persian cat, followed by the Maine Coon cat",
"can weigh just 4 lbs (1.8 kg), or about five large cans of",
"tabby. Legend says that tabby cats have an “M” for Mohammed on top",
"the root of the superstition that a cat will smother a sleeping baby",
"soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people are bitten by cats in",
"placed in the family tomb or in a pet cemetery with tiny mummies",
"meters), due largely to their “righting reflex.” The eyes and balance organs in",
"and Australia, black cats are considered lucky.\", \"(33) The most popular pedigreed cat",
"like pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh, and remember, next Friday",
"may be the root of the superstition that a cat will smother a",
"black vampire cat, sucking the blood from sleeping babies. This may be the",
"19 kittens, of which 15 survived.\", \"(26) Smuggling a cat out of ancient",
"\"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\":",
"a French cat named Felicette (a.k.a. “Astrocat”) In 1963, France blasted the cat",
"its life.\", \"(48) In the original Italian version of Cinderella, the benevolent fairy",
"a litter of between one and nine kittens. The largest known litter ever",
"term pisica and the root of secondary words in Lithuanian (puz) and Low",
"from the right side of the brain go mostly to the left eye.",
"every claw on a cat’s paw points the same way. To get down",
"being soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people are bitten by cats",
"[ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\", \"I like",
"folklore recounts that Adam’s first wife, Lilith, became a black vampire cat, sucking",
"the world, with approximately 40 recognized breeds.\", \"(9) Approximately 24 cat skins can",
"to get a cat’s attention. As a slang word for the female pudenda,",
"rest his hand on the cat’s head.\", \"(32) While many parts of Europe",
"smallest wildcat today is the Black-footed cat. The females are less than 20",
"the water because their fur does not insulate well when it’s wet. The",
"at random for trigger in multireplydict: try: if trigger in messagetext.lower(): replytext =",
"\"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ],",
"for help protecting all the food he stored on the ark from being",
"m) long (about the size of a small car) and weigh up to",
"than 12 feet (3.6 m) long (about the size of a small car)",
"a woman’s body and a cat’s head.\", \"(31) Mohammed loved cats and reportedly",
"the oldest breed of cat. In fact, the breed is so ancient that",
"Alice in Wonderland. With the ability to disappear, this mysterious character embodies the",
"“M” for Mohammed on top of their heads because Mohammad would often rest",
"trigger in singlereplydict: try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext)",
"Asia, its coat has a unique texture that makes it water resistant.\", \"(40)",
"Carroll’s Alice in Wonderland. With the ability to disappear, this mysterious character embodies",
"wrappings and carted off to be used by farmers in England and the",
"a cat named “<NAME>”. He cost his owner $50,000, making him one of",
"killing of cats led to an explosion of the rat population, which exacerbated",
"Mohammed on top of their heads because Mohammad would often rest his hand",
"coats resembled the famous wavy patterns in the silk produced in this city.\",",
"\"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do",
"\"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\",",
"pudenda, it could be associated with the connotation of a cat being soft,",
"a cat purrs by vibrating vocal folds deep in the throat. To do",
"This grave predates early Egyptian art depicting cats by 4,000 years or more.\",",
"carted off to be used by farmers in England and the U.S. for",
"pedigreed cat is the Persian cat, followed by the Maine Coon cat and",
"\"(11) During the time of the Spanish Inquisition, Pope Innocent VIII condemned cats",
"import os import telegram import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger",
"left side of the brain go to mostly the right eye and the",
"cats is called a “clowder”.\", \"(5) A cat can’t climb head first down",
"glands around its face. The tail area and paws also carry the cat’s",
"a cat’s head.\", \"(31) Mohammed loved cats and reportedly his favorite cat, Muezza,",
"lbs (1.8 kg), or about five large cans of cat food. The largest",
"Middle Ages, cats were associated with withcraft, and on St. John’s Day, people",
"swimming. Bred in central Asia, its coat has a unique texture that makes",
"and Low German puus. Some scholars suggest that “puss” could be imitative of",
"to feles, or wild cat.\", \"(15) The term “puss” is the root of",
"1:1 mapped responses for trigger in singlereplydict: try: if trigger in messagetext.lower(): replytext",
"just 4 lbs (1.8 kg), or about five large cans of cat food.",
"nine kittens. The largest known litter ever produced was 19 kittens, of which",
"smother a sleeping baby or suck out the child’s breath.\", \"(45) Perhaps the",
"was 19 kittens, of which 15 survived.\", \"(26) Smuggling a cat out of",
"distance.\", \"(21) A cat rubs against people not only to be affectionate but",
"The eyes and balance organs in the inner ear tell it where it",
"right side of the brain go mostly to the left eye. This causes",
"toss the cats into bonfires. On holy days, people celebrated by tossing cats",
"and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [",
"lived about 30 million years ago. Scientists called it the Proailurus, which means",
"🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary",
"if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext =",
"by 4,000 years or more.\", \"(11) During the time of the Spanish Inquisition,",
"act as compasses.\", ], } def webhook(request): if request.method == \"POST\": update =",
"human.\", \"(20) A cat can travel at a top speed of approximately 31",
"suggest that “puss” could be imitative of the hissing sound used to get",
"each side of its face.\", \"(43) A cat’s eyesight is both better and",
"the most famous comic cat is the Cheshire Cat in Lewis Carroll’s Alice",
"color as well as humans do. Scientists believe grass appears red to cats.\",",
"┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\",",
"million cats compared to 63 million dogs. Over 30% of households in North",
"dog’s. And a cat can hear high-frequency sounds up to two octaves higher",
"hand on the cat’s head.\", \"(32) While many parts of Europe and North",
"can travel at a top speed of approximately 31 mph (49 km) over",
"the back.\", \"I like turtles.\", \"I like pie.\", \"Das ist ein rucksack auf",
"in the throat. To do this, a muscle in the larynx opens and",
"The earliest ancestor of the modern cat lived about 30 million years ago.",
"tabby cats have an “M” for Mohammed on top of their heads because",
"insulate the ears are called “ear furnishings.”\", \"(50) The ability of a cat",
"ancient Egypt was punishable by death. Phoenician traders eventually succeeded in smuggling felines,",
"Friday is Swedish luggage day, so, you know, if you want to, go",
"During the time of the Spanish Inquisition, Pope Innocent VIII condemned cats as",
"because Mohammad would often rest his hand on the cat’s head.\", \"(32) While",
"view. It’s worse because they don’t see color as well as humans do.",
"is the Black-footed cat. The females are less than 20 inches (50 cm)",
"and the Siamese cat.\", \"(34) The smallest pedigreed cat is a Singapura, which",
"It is better because cats can see in much dimmer light and they",
"million cats are eaten in Asia.\", \"(8) There are more than 500 million",
"Unfortunately, the widespread killing of cats led to an explosion of the rat",
"\"(47) On average, cats spend 2/3 of every day sleeping. That means a",
"the Proailurus, which means “first cat” in Greek. The group of animals that",
"cat.\", \"(34) The smallest pedigreed cat is a Singapura, which can weigh just",
"65 feet (20 meters), due largely to their “righting reflex.” The eyes and",
"the Cheshire Cat in Lewis Carroll’s Alice in Wonderland. With the ability to",
"principal word for “cat” in the Romanian term pisica and the root of",
"than a human.\", \"(20) A cat can travel at a top speed of",
"The largest pedigreed cats are Maine Coon cats, which can weigh 25 lbs",
"called “psi-traveling.” Experts think cats either use the angle of the sunlight to",
"with single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\",",
"grave predates early Egyptian art depicting cats by 4,000 years or more.\", \"(11)",
"is a Singapura, which can weigh just 4 lbs (1.8 kg), or about",
"the left eye. This causes some double vision, which the cat tries to",
"church towers.\", \"(13) The first cat in space was a French cat named",
"because every claw on a cat’s paw points the same way. To get",
"cost his owner $50,000, making him one of the most expensive cats ever.\",",
"cat. The females are less than 20 inches (50 cm) long and can",
"Inquisition, Pope Innocent VIII condemned cats as evil and thousands of cats were",
"by cats in the U.S. annually.\", \"(17) Cats are North America’s most popular",
"be the root of the superstition that a cat will smother a sleeping",
"larynx opens and closes the air passage about 25 times per second.\", \"(23)",
"cat was embalmed with a sculpted wooden mask and the tiny mummy was",
"of trigger words with multiple random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\",",
"a cat’s hairball is a “bezoar”.\", \"(4) A group of cats is called",
"cats have an “M” for Mohammed on top of their heads because Mohammad",
"\"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔",
"\"(26) Smuggling a cat out of ancient Egypt was punishable by death. Phoenician",
"\"(41) The first commercially cloned pet was a cat named “<NAME>”. He cost",
"child’s breath.\", \"(45) Perhaps the most famous comic cat is the Cheshire Cat",
"opens and closes the air passage about 25 times per second.\", \"(23) When",
"of the Black Death.\", \"(12) During the Middle Ages, cats were associated with",
"\"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\":",
"for trigger in singlereplydict: try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id,",
"remember, next Friday is Swedish luggage day, so, you know, if you want",
"Even cats without a tail have this ability.\", \"(36) Some Siamese cats appear",
"known pet cat was recently found in a 9,500-year-old grave on the Mediterranean",
"neurological signals back to Earth. She survived the trip.\", \"(14) The group of",
"believe that a cat purrs by vibrating vocal folds deep in the throat.",
"Mau is probably the oldest breed of cat. In fact, the breed is",
"luggage day, so, you know, if you want to, go ahead and wear",
"their fur does not insulate well when it’s wet. The Turkish Van, however,",
"The biggest wildcat today is the Siberian Tiger. It can be more than",
"= telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single 1:1 reply singlereplydict =",
"day, so, you know, if you want to, go ahead and wear a",
"mutation in a key taste receptor.\", \"(2) When a cat chases its prey,",
"into bonfires. On holy days, people celebrated by tossing cats from church towers.\",",
"its prey, it keeps its head level. Dogs and humans bob their heads",
"recently found in a 9,500-year-old grave on the Mediterranean island of Cyprus. This",
"people all over Europe would stuff them into sacks and toss the cats",
"to a dog’s. Both humans and cats have identical regions in their brains",
"the size of a small car) and weigh up to 700 pounds (317",
"♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\":",
"America consider the black cat a sign of bad luck, in Britain and",
"\"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", }",
"\"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\",",
"were the first to domesticate cats, the oldest known pet cat was recently",
"mummies of mice.\", \"(24) In 1888, more than 300,000 mummified cats were found",
"outer space. Electrodes implanted in her brains sent neurological signals back to Earth.",
"\"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], #",
"whiskers on each side of its face.\", \"(43) A cat’s eyesight is both",
"to be selected at random for trigger in multireplydict: try: if trigger in",
"10.\", \"(7) Every year, nearly four million cats are eaten in Asia.\", \"(8)",
"recounts that Adam’s first wife, Lilith, became a black vampire cat, sucking the",
"was a cat named “<NAME>”. He cost his owner $50,000, making him one",
"legend, Noah prayed to God for help protecting all the food he stored",
"Some scholars suggest that “puss” could be imitative of the hissing sound used",
"Singapura, which can weigh just 4 lbs (1.8 kg), or about five large",
"mummified cats were found an Egyptian cemetery. They were stripped of their wrappings",
"the food he stored on the ark from being eaten by rats. In",
"inches (50 cm) long and can weigh as little as 2.5 lbs (1.2",
"the Romanian term pisica and the root of secondary words in Lithuanian (puz)",
"angle of the sunlight to find their way or that cats have magnetized",
"benevolent fairy godmother figure was a cat.\", \"(49) The little tufts of hair",
"sucking the blood from sleeping babies. This may be the root of the",
"Death.\", \"(12) During the Middle Ages, cats were associated with withcraft, and on",
"are Maine Coon cats, which can weigh 25 lbs (11.3 kg), or nearly",
"would stuff them into sacks and toss the cats into bonfires. On holy",
"their eyebrows. They also held elaborate funerals during which they drank wine and",
"15 survived.\", \"(26) Smuggling a cat out of ancient Egypt was punishable by",
"In the original Italian version of Cinderella, the benevolent fairy godmother figure was",
"], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do not have",
"get down from a tree, a cat must back down.\", \"(6) Cats make",
"multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for",
"cat can land on its feet. Even cats without a tail have this",
"believe this is due to a mutation in a key taste receptor.\", \"(2)",
"be used by farmers in England and the U.S. for fertilizer.\", \"(25) Most",
"makes it water resistant.\", \"(40) The Egyptian Mau is probably the oldest breed",
"is the root of the principal word for “cat” in the Romanian term",
"receptor.\", \"(2) When a cat chases its prey, it keeps its head level.",
"cat can hear high-frequency sounds up to two octaves higher than a human.\",",
"cemetery. They were stripped of their wrappings and carted off to be used",
"this city.\", \"(38) A cat can jump up to five times its own",
"to mark out its territory with scent glands around its face. The tail",
"cat purrs. Most veterinarians believe that a cat purrs by vibrating vocal folds",
"the goddess Bast, who had a woman’s body and a cat’s head.\", \"(31)",
"held elaborate funerals during which they drank wine and beat their breasts. The",
"a top speed of approximately 31 mph (49 km) over a short distance.\",",
"and down.\", \"(3) The technical term for a cat’s hairball is a “bezoar”.\",",
"\"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\",",
"\"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\":",
"\"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\",",
"in Baghdad, Iraq. Tabbies got their name because their striped coats resembled the",
"with tiny mummies of mice.\", \"(24) In 1888, more than 300,000 mummified cats",
"more than 500 million domestic cats in the world, with approximately 40 recognized",
"drank wine and beat their breasts. The cat was embalmed with a sculpted",
"“ear furnishings.”\", \"(50) The ability of a cat to find its way home",
"were burned. Unfortunately, the widespread killing of cats led to an explosion of",
"the cat tries to correct by “crossing” its eyes.\", \"(37) Researchers believe the",
"“cat” in the Romanian term pisica and the root of secondary words in",
"often rest his hand on the cat’s head.\", \"(32) While many parts of",
"\"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\", \"I like turtles.\", \"I like",
"in Lithuanian (puz) and Low German puus. Some scholars suggest that “puss” could",
"made the lion sneeze, and out popped a cat.\", \"(19) A cat’s hearing",
"\"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\":",
"or that cats have magnetized cells in their brains that act as compasses.\",",
"eye and the nerves from the right side of the brain go mostly",
"tufts of hair in a cat’s ear that help keep out dirt direct",
"right eye and the nerves from the right side of the brain go",
"a coat.\", \"(10) While it is commonly thought that the ancient Egyptians were",
"can jump up to five times its own height in a single bound.\",",
"(49 km) over a short distance.\", \"(21) A cat rubs against people not",
"this is due to a mutation in a key taste receptor.\", \"(2) When",
"it water resistant.\", \"(40) The Egyptian Mau is probably the oldest breed of",
"a small car) and weigh up to 700 pounds (317 kg).\", \"(29) A",
"import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single 1:1",
"Day, people all over Europe would stuff them into sacks and toss the",
"England and the U.S. for fertilizer.\", \"(25) Most cats give birth to a",
"of cats is called a “clowder”.\", \"(5) A cat can’t climb head first",
"a human brain than it is to a dog’s. Both humans and cats",
"have identical regions in their brains that are responsible for emotions.\", \"(30) Many",
"a dog’s. And a cat can hear high-frequency sounds up to two octaves",
"pet cemetery with tiny mummies of mice.\", \"(24) In 1888, more than 300,000",
"than a dog’s. And a cat can hear high-frequency sounds up to two",
"bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\",",
"about 10.\", \"(7) Every year, nearly four million cats are eaten in Asia.\",",
"think cats either use the angle of the sunlight to find their way",
"sounds up to two octaves higher than a human.\", \"(20) A cat can",
"When a family cat died in ancient Egypt, family members would mourn by",
"to disappear, this mysterious character embodies the magic and sorcery historically associated with",
"brain than it is to a dog’s. Both humans and cats have identical",
"and can weigh as little as 2.5 lbs (1.2 kg).\", \"(47) On average,",
"are considered lucky.\", \"(33) The most popular pedigreed cat is the Persian cat,",
"Some cats have survived falls of over 65 feet (20 meters), due largely",
"of its life.\", \"(48) In the original Italian version of Cinderella, the benevolent",
"off to be used by farmers in England and the U.S. for fertilizer.\",",
"own a cat.\", \"(18) According to Hebrew legend, Noah prayed to God for",
"domesticate cats, the oldest known pet cat was recently found in a 9,500-year-old",
"got their name because their striped coats resembled the famous wavy patterns in",
"hate the water because their fur does not insulate well when it’s wet.",
"Britain and Australia, black cats are considered lucky.\", \"(33) The most popular pedigreed",
"make about 100 different sounds. Dogs make only about 10.\", \"(7) Every year,",
"This may be the root of the superstition that a cat will smother",
"it where it is in space so the cat can land on its",
"ear that help keep out dirt direct sounds into the ear, and insulate",
"cats have magnetized cells in their brains that act as compasses.\", ], }",
"Deutsch!\", \"Oh, and remember, next Friday is Swedish luggage day, so, you know,",
"Perhaps the most famous comic cat is the Cheshire Cat in Lewis Carroll’s",
"🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\",",
"from a tree, a cat must back down.\", \"(6) Cats make about 100",
"Pope Innocent VIII condemned cats as evil and thousands of cats were burned.",
"two octaves higher than a human.\", \"(20) A cat can travel at a",
"short distance.\", \"(21) A cat rubs against people not only to be affectionate",
"vibrating vocal folds deep in the throat. To do this, a muscle in",
"is the Cheshire Cat in Lewis Carroll’s Alice in Wonderland. With the ability",
"responses for trigger in singlereplydict: try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger]",
"their heads up and down.\", \"(3) The technical term for a cat’s hairball",
"however, is one cat that likes swimming. Bred in central Asia, its coat",
"that Adam’s first wife, Lilith, became a black vampire cat, sucking the blood",
"{ \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\",",
"try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass",
"territory with scent glands around its face. The tail area and paws also",
"eaten by rats. In reply, God made the lion sneeze, and out popped",
"four million cats are eaten in Asia.\", \"(8) There are more than 500",
"a cat can hear high-frequency sounds up to two octaves higher than a",
"cats have survived falls of over 65 feet (20 meters), due largely to",
"the nerves from the right side of the brain go mostly to the",
"head.\", \"(32) While many parts of Europe and North America consider the black",
"Swedish luggage day, so, you know, if you want to, go ahead and",
"a tree, a cat must back down.\", \"(6) Cats make about 100 different",
"only about 10.\", \"(7) Every year, nearly four million cats are eaten in",
"without a tail have this ability.\", \"(36) Some Siamese cats appear cross-eyed because",
"not insulate well when it’s wet. The Turkish Van, however, is one cat",
"and balance organs in the inner ear tell it where it is in",
"multireplydict: try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError:",
"only to be affectionate but also to mark out its territory with scent",
"the right side of the brain go mostly to the left eye. This",
"the U.S. for fertilizer.\", \"(25) Most cats give birth to a litter of",
"cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first wife, Lilith, became a black",
"which they sold to rich people in Athens and other important cities.\", \"(27)",
"fur does not insulate well when it’s wet. The Turkish Van, however, is",
"In 1888, more than 300,000 mummified cats were found an Egyptian cemetery. They",
"skins can make a coat.\", \"(10) While it is commonly thought that the",
"and sorcery historically associated with cats.\", \"(46) The smallest wildcat today is the",
"and on St. John’s Day, people all over Europe would stuff them into",
"sleeping. That means a nine-year-old cat has been awake for only three years",
"According to Hebrew legend, Noah prayed to God for help protecting all the",
"While many parts of Europe and North America consider the black cat a",
"their striped coats resembled the famous wavy patterns in the silk produced in",
"smallest pedigreed cat is a Singapura, which can weigh just 4 lbs (1.8",
"Scientists believe grass appears red to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s",
"update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped responses for trigger in singlereplydict:",
"being eaten by rats. In reply, God made the lion sneeze, and out",
"ear, and insulate the ears are called “ear furnishings.”\", \"(50) The ability of",
"know, if you want to, go ahead and wear a bäckpäck.\", ], \"dumpsterfire\":",
"was embalmed with a sculpted wooden mask and the tiny mummy was placed",
"its feet. Even cats without a tail have this ability.\", \"(36) Some Siamese",
"effects of the Black Death.\", \"(12) During the Middle Ages, cats were associated",
"tomb or in a pet cemetery with tiny mummies of mice.\", \"(24) In",
"jump up to five times its own height in a single bound.\", \"(39)",
"little as 2.5 lbs (1.2 kg).\", \"(47) On average, cats spend 2/3 of",
"cats were found an Egyptian cemetery. They were stripped of their wrappings and",
"one of the most expensive cats ever.\", \"(42) A cat usually has about",
"Cats make about 100 different sounds. Dogs make only about 10.\", \"(7) Every",
"Cat in Lewis Carroll’s Alice in Wonderland. With the ability to disappear, this",
"and a cat’s head.\", \"(31) Mohammed loved cats and reportedly his favorite cat,",
"sunlight to find their way or that cats have magnetized cells in their",
"side of its face.\", \"(43) A cat’s eyesight is both better and worse",
"・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔",
"woman’s body and a cat’s head.\", \"(31) Mohammed loved cats and reportedly his",
"in Athens and other important cities.\", \"(27) The earliest ancestor of the modern",
"so ancient that its name is the Egyptian word for “cat.”\", \"(41) The",
"known litter ever produced was 19 kittens, of which 15 survived.\", \"(26) Smuggling",
"considered lucky.\", \"(33) The most popular pedigreed cat is the Persian cat, followed",
"several options to be selected at random for trigger in multireplydict: try: if",
"A cat’s eyesight is both better and worse than humans. It is better",
"million domestic cats in the world, with approximately 40 recognized breeds.\", \"(9) Approximately",
"pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh, and remember, next Friday is",
"root of the superstition that a cat will smother a sleeping baby or",
"A cat can travel at a top speed of approximately 31 mph (49",
"Mohammad would often rest his hand on the cat’s head.\", \"(32) While many",
"same way. To get down from a tree, a cat must back down.\",",
"Noah prayed to God for help protecting all the food he stored on",
"as little as 2.5 lbs (1.2 kg).\", \"(47) On average, cats spend 2/3",
"like turtles.\", \"I like pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh, and",
"“crossing” its eyes.\", \"(37) Researchers believe the word “tabby” comes from Attabiyah, a",
"the widespread killing of cats led to an explosion of the rat population,",
"famous wavy patterns in the silk produced in this city.\", \"(38) A cat",
"\"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵",
"trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these",
"random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the",
"blood from sleeping babies. This may be the root of the superstition that",
"city.\", \"(38) A cat can jump up to five times its own height",
"\"I like pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh, and remember, next",
"the ark from being eaten by rats. In reply, God made the lion",
"celebrated by tossing cats from church towers.\", \"(13) The first cat in space",
"Legend says that tabby cats have an “M” for Mohammed on top of",
"because the nerves from the left side of the brain go to mostly",
"a cat’s attention. As a slang word for the female pudenda, it could",
"and nine kittens. The largest known litter ever produced was 19 kittens, of",
"words with multiple random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\",",
"To get down from a tree, a cat must back down.\", \"(6) Cats",
"of cats led to an explosion of the rat population, which exacerbated the",
"the cat into outer space. Electrodes implanted in her brains sent neurological signals",
"\"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\":",
"} # dictionary of trigger words with multiple random responses multireplydict = {",
"direct 1:1 mapped responses for trigger in singlereplydict: try: if trigger in messagetext.lower():",
"breeds.\", \"(9) Approximately 24 cat skins can make a coat.\", \"(10) While it",
"this, a muscle in the larynx opens and closes the air passage about",
"of cat. In fact, the breed is so ancient that its name is",
"for “cat” in the Romanian term pisica and the root of secondary words",
"every day sleeping. That means a nine-year-old cat has been awake for only",
"due largely to their “righting reflex.” The eyes and balance organs in the",
"cat weighs.\", \"(35) Some cats have survived falls of over 65 feet (20",
"sounds. Dogs make only about 10.\", \"(7) Every year, nearly four million cats",
"and weigh up to 700 pounds (317 kg).\", \"(29) A cat’s brain is",
"Siamese cats appear cross-eyed because the nerves from the left side of the",
"On average, cats spend 2/3 of every day sleeping. That means a nine-year-old",
"trigger words with single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\":",
"\"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct",
"= telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped",
"funerals during which they drank wine and beat their breasts. The cat was",
"(3.6 m) long (about the size of a small car) and weigh up",
"40 recognized breeds.\", \"(9) Approximately 24 cat skins can make a coat.\", \"(10)",
"against people not only to be affectionate but also to mark out its",
"dictionary of trigger words with multiple random responses multireplydict = { \"backpack\": [",
"tries to correct by “crossing” its eyes.\", \"(37) Researchers believe the word “tabby”",
"they have a wider peripheral view. It’s worse because they don’t see color",
"the ear, and insulate the ears are called “ear furnishings.”\", \"(50) The ability",
"named Felicette (a.k.a. “Astrocat”) In 1963, France blasted the cat into outer space.",
"Baghdad, Iraq. Tabbies got their name because their striped coats resembled the famous",
"widespread killing of cats led to an explosion of the rat population, which",
"cat.\", \"(18) According to Hebrew legend, Noah prayed to God for help protecting",
"have several options to be selected at random for trigger in multireplydict: try:",
"the superstition that a cat will smother a sleeping baby or suck out",
"\"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\", \"I",
"selected at random for trigger in multireplydict: try: if trigger in messagetext.lower(): replytext",
"ever produced was 19 kittens, of which 15 survived.\", \"(26) Smuggling a cat",
"magnetized cells in their brains that act as compasses.\", ], } def webhook(request):",
"one cat that likes swimming. Bred in central Asia, its coat has a",
"Maine Coon cats, which can weigh 25 lbs (11.3 kg), or nearly twice",
"most famous comic cat is the Cheshire Cat in Lewis Carroll’s Alice in",
"kg).\", \"(29) A cat’s brain is biologically more similar to a human brain",
"likes swimming. Bred in central Asia, its coat has a unique texture that",
"\"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\",",
"the family tomb or in a pet cemetery with tiny mummies of mice.\",",
"brains that are responsible for emotions.\", \"(30) Many Egyptians worshipped the goddess Bast,",
"cat named Felicette (a.k.a. “Astrocat”) In 1963, France blasted the cat into outer",
"years ago.\", \"(28) The biggest wildcat today is the Siberian Tiger. It can",
"opposed to feles, or wild cat.\", \"(15) The term “puss” is the root",
"\"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\",",
"eyebrows. They also held elaborate funerals during which they drank wine and beat",
"up to two octaves higher than a human.\", \"(20) A cat can travel",
"to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first wife, Lilith, became a",
"Black-footed cat. The females are less than 20 inches (50 cm) long and",
"and reportedly his favorite cat, Muezza, was a tabby. Legend says that tabby",
"cats are considered lucky.\", \"(33) The most popular pedigreed cat is the Persian",
"in the inner ear tell it where it is in space so the",
"in a 9,500-year-old grave on the Mediterranean island of Cyprus. This grave predates",
"\"(49) The little tufts of hair in a cat’s ear that help keep",
"and toss the cats into bonfires. On holy days, people celebrated by tossing",
"and cats have identical regions in their brains that are responsible for emotions.\",",
"felines, which they sold to rich people in Athens and other important cities.\",",
"a unique texture that makes it water resistant.\", \"(40) The Egyptian Mau is",
"root of the principal word for “cat” in the Romanian term pisica and",
"first wife, Lilith, became a black vampire cat, sucking the blood from sleeping",
"survived the trip.\", \"(14) The group of words associated with cat (catt, cath,",
"🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\":",
"\"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\":",
"9,500-year-old grave on the Mediterranean island of Cyprus. This grave predates early Egyptian",
"its eyes.\", \"(37) Researchers believe the word “tabby” comes from Attabiyah, a neighborhood",
"different sounds. Dogs make only about 10.\", \"(7) Every year, nearly four million",
"died in ancient Egypt, family members would mourn by shaving off their eyebrows.",
"its name is the Egyptian word for “cat.”\", \"(41) The first commercially cloned",
"an Egyptian cemetery. They were stripped of their wrappings and carted off to",
"the first to domesticate cats, the oldest known pet cat was recently found",
"is better than a dog’s. And a cat can hear high-frequency sounds up",
"\"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\",",
"well as humans do. Scientists believe grass appears red to cats.\", \"(44) Spanish-Jewish",
"\"(15) The term “puss” is the root of the principal word for “cat”",
"to find its way home is called “psi-traveling.” Experts think cats either use",
"\"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\",",
"Low German puus. Some scholars suggest that “puss” could be imitative of the",
"area and paws also carry the cat’s scent.\", \"(22) Researchers are unsure exactly",
"shaving off their eyebrows. They also held elaborate funerals during which they drank",
"Siamese cat.\", \"(34) The smallest pedigreed cat is a Singapura, which can weigh",
"During the Middle Ages, cats were associated with withcraft, and on St. John’s",
"worshipped the goddess Bast, who had a woman’s body and a cat’s head.\",",
"\"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷",
"the cats into bonfires. On holy days, people celebrated by tossing cats from",
"an “M” for Mohammed on top of their heads because Mohammad would often",
"a Singapura, which can weigh just 4 lbs (1.8 kg), or about five",
"down from a tree, a cat must back down.\", \"(6) Cats make about",
"feet. Even cats without a tail have this ability.\", \"(36) Some Siamese cats",
"A cat can jump up to five times its own height in a",
"in their brains that act as compasses.\", ], } def webhook(request): if request.method",
"a “bezoar”.\", \"(4) A group of cats is called a “clowder”.\", \"(5) A",
"the root of the principal word for “cat” in the Romanian term pisica",
"go mostly to the left eye. This causes some double vision, which the",
"called “ear furnishings.”\", \"(50) The ability of a cat to find its way",
"that likes swimming. Bred in central Asia, its coat has a unique texture",
"wife, Lilith, became a black vampire cat, sucking the blood from sleeping babies.",
"bound.\", \"(39) Cats hate the water because their fur does not insulate well",
"cat was recently found in a 9,500-year-old grave on the Mediterranean island of",
"\"(40) The Egyptian Mau is probably the oldest breed of cat. In fact,",
"100 different sounds. Dogs make only about 10.\", \"(7) Every year, nearly four",
"five times its own height in a single bound.\", \"(39) Cats hate the",
"The largest known litter ever produced was 19 kittens, of which 15 survived.\",",
"\"(8) There are more than 500 million domestic cats in the world, with",
"higher than a human.\", \"(20) A cat can travel at a top speed",
"travel at a top speed of approximately 31 mph (49 km) over a",
"\"(37) Researchers believe the word “tabby” comes from Attabiyah, a neighborhood in Baghdad,",
"is a “bezoar”.\", \"(4) A group of cats is called a “clowder”.\", \"(5)",
"the left side of the brain go to mostly the right eye and",
"of Cyprus. This grave predates early Egyptian art depicting cats by 4,000 years",
"The tail area and paws also carry the cat’s scent.\", \"(22) Researchers are",
"ability.\", \"(36) Some Siamese cats appear cross-eyed because the nerves from the left",
"in the silk produced in this city.\", \"(38) A cat can jump up",
"== \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text #",
"yeah... the pack for the back.\", \"I like turtles.\", \"I like pie.\", \"Das",
"were stripped of their wrappings and carted off to be used by farmers",
"twice as much as an average cat weighs.\", \"(35) Some cats have survived",
"of the sunlight to find their way or that cats have magnetized cells",
"North America’s most popular pets: there are 73 million cats compared to 63",
"make only about 10.\", \"(7) Every year, nearly four million cats are eaten",
"but also to mark out its territory with scent glands around its face.",
"cat lived about 30 million years ago. Scientists called it the Proailurus, which",
"go to mostly the right eye and the nerves from the right side",
"also held elaborate funerals during which they drank wine and beat their breasts.",
"million years ago. Scientists called it the Proailurus, which means “first cat” in",
"\"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\":",
"implanted in her brains sent neurological signals back to Earth. She survived the",
"wildcat today is the Siberian Tiger. It can be more than 12 feet",
"to five times its own height in a single bound.\", \"(39) Cats hate",
"its own height in a single bound.\", \"(39) Cats hate the water because",
"cats ever.\", \"(42) A cat usually has about 12 whiskers on each side",
"cat is a Singapura, which can weigh just 4 lbs (1.8 kg), or",
"about 100 different sounds. Dogs make only about 10.\", \"(7) Every year, nearly",
"in ancient Egypt, family members would mourn by shaving off their eyebrows. They",
"cat must back down.\", \"(6) Cats make about 100 different sounds. Dogs make",
"Turkish Van, however, is one cat that likes swimming. Bred in central Asia,",
"\"(42) A cat usually has about 12 whiskers on each side of its",
"telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single 1:1 reply singlereplydict = {",
"paws also carry the cat’s scent.\", \"(22) Researchers are unsure exactly how a",
"more similar to a human brain than it is to a dog’s. Both",
"os import telegram import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words",
"air passage about 25 times per second.\", \"(23) When a family cat died",
"Earth. She survived the trip.\", \"(14) The group of words associated with cat",
"times per second.\", \"(23) When a family cat died in ancient Egypt, family",
"30% of households in North America own a cat.\", \"(18) According to Hebrew",
"litter ever produced was 19 kittens, of which 15 survived.\", \"(26) Smuggling a",
"wider peripheral view. It’s worse because they don’t see color as well as",
"ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\":",
"is the Persian cat, followed by the Maine Coon cat and the Siamese",
"In fact, the breed is so ancient that its name is the Egyptian",
"on St. John’s Day, people all over Europe would stuff them into sacks",
"for trigger in multireplydict: try: if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id,",
"throat. To do this, a muscle in the larynx opens and closes the",
"and the tiny mummy was placed in the family tomb or in a",
"“Astrocat”) In 1963, France blasted the cat into outer space. Electrodes implanted in",
"a cat.\", \"(49) The little tufts of hair in a cat’s ear that",
"way home is called “psi-traveling.” Experts think cats either use the angle of",
"by tossing cats from church towers.\", \"(13) The first cat in space was",
"hissing sound used to get a cat’s attention. As a slang word for",
"important cities.\", \"(27) The earliest ancestor of the modern cat lived about 30",
"humans bob their heads up and down.\", \"(3) The technical term for a",
"They were stripped of their wrappings and carted off to be used by",
"Greek. The group of animals that pet cats belong to emerged around 12",
"messagetext = update.effective_message.text # direct 1:1 mapped responses for trigger in singlereplydict: try:",
"own height in a single bound.\", \"(39) Cats hate the water because their",
"by farmers in England and the U.S. for fertilizer.\", \"(25) Most cats give",
"St. John’s Day, people all over Europe would stuff them into sacks and",
"\"(16) Approximately 40,000 people are bitten by cats in the U.S. annually.\", \"(17)",
"world, with approximately 40 recognized breeds.\", \"(9) Approximately 24 cat skins can make",
"cats compared to 63 million dogs. Over 30% of households in North America",
"which can weigh just 4 lbs (1.8 kg), or about five large cans",
"not have a sweet tooth. Scientists believe this is due to a mutation",
"are bitten by cats in the U.S. annually.\", \"(17) Cats are North America’s",
"consider the black cat a sign of bad luck, in Britain and Australia,",
"Athens and other important cities.\", \"(27) The earliest ancestor of the modern cat",
"animals that pet cats belong to emerged around 12 million years ago.\", \"(28)",
"The most popular pedigreed cat is the Persian cat, followed by the Maine",
"ark from being eaten by rats. In reply, God made the lion sneeze,",
"], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\",",
"first down a tree because every claw on a cat’s paw points the",
"\"I like turtles.\", \"I like pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh,",
"keeps its head level. Dogs and humans bob their heads up and down.\",",
"the time of the Spanish Inquisition, Pope Innocent VIII condemned cats as evil",
"use the angle of the sunlight to find their way or that cats",
"eyes.\", \"(37) Researchers believe the word “tabby” comes from Attabiyah, a neighborhood in",
"\"Das ist ein rucksack auf Deutsch!\", \"Oh, and remember, next Friday is Swedish",
"from the left side of the brain go to mostly the right eye",
"} def webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id =",
"lion sneeze, and out popped a cat.\", \"(19) A cat’s hearing is better",
"side of the brain go to mostly the right eye and the nerves",
"owner $50,000, making him one of the most expensive cats ever.\", \"(42) A",
"million dogs. Over 30% of households in North America own a cat.\", \"(18)",
"\"(35) Some cats have survived falls of over 65 feet (20 meters), due",
"Both humans and cats have identical regions in their brains that are responsible",
"called it the Proailurus, which means “first cat” in Greek. The group of",
"character embodies the magic and sorcery historically associated with cats.\", \"(46) The smallest",
"to mostly the right eye and the nerves from the right side of",
"per second.\", \"(23) When a family cat died in ancient Egypt, family members",
"disappear, this mysterious character embodies the magic and sorcery historically associated with cats.\",",
"cat skins can make a coat.\", \"(10) While it is commonly thought that",
"black cat a sign of bad luck, in Britain and Australia, black cats",
"He cost his owner $50,000, making him one of the most expensive cats",
"taste receptor.\", \"(2) When a cat chases its prey, it keeps its head",
"for Mohammed on top of their heads because Mohammad would often rest his",
"for the female pudenda, it could be associated with the connotation of a",
"original Italian version of Cinderella, the benevolent fairy godmother figure was a cat.\",",
"= update.effective_message.text # direct 1:1 mapped responses for trigger in singlereplydict: try: if",
"signals back to Earth. She survived the trip.\", \"(14) The group of words",
"Italian version of Cinderella, the benevolent fairy godmother figure was a cat.\", \"(49)",
"causes some double vision, which the cat tries to correct by “crossing” its",
"earliest ancestor of the modern cat lived about 30 million years ago. Scientists",
"largely to their “righting reflex.” The eyes and balance organs in the inner",
"goddess Bast, who had a woman’s body and a cat’s head.\", \"(31) Mohammed",
"water because their fur does not insulate well when it’s wet. The Turkish",
"who had a woman’s body and a cat’s head.\", \"(31) Mohammed loved cats",
"term “puss” is the root of the principal word for “cat” in the",
"of every day sleeping. That means a nine-year-old cat has been awake for",
"down.\", \"(3) The technical term for a cat’s hairball is a “bezoar”.\", \"(4)",
"the oldest known pet cat was recently found in a 9,500-year-old grave on",
"long and can weigh as little as 2.5 lbs (1.2 kg).\", \"(47) On",
"up to 700 pounds (317 kg).\", \"(29) A cat’s brain is biologically more",
"“tabby” comes from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got their name",
"wild cat.\", \"(15) The term “puss” is the root of the principal word",
"making him one of the most expensive cats ever.\", \"(42) A cat usually",
"tail have this ability.\", \"(36) Some Siamese cats appear cross-eyed because the nerves",
"help protecting all the food he stored on the ark from being eaten",
"is Swedish luggage day, so, you know, if you want to, go ahead",
"word for “cat” in the Romanian term pisica and the root of secondary",
"home is called “psi-traveling.” Experts think cats either use the angle of the",
"one and nine kittens. The largest known litter ever produced was 19 kittens,",
"family members would mourn by shaving off their eyebrows. They also held elaborate",
"that tabby cats have an “M” for Mohammed on top of their heads",
"can hear high-frequency sounds up to two octaves higher than a human.\", \"(20)",
"a dog’s. Both humans and cats have identical regions in their brains that",
"of Cinderella, the benevolent fairy godmother figure was a cat.\", \"(49) The little",
"The little tufts of hair in a cat’s ear that help keep out",
"breath.\", \"(45) Perhaps the most famous comic cat is the Cheshire Cat in",
"Cats hate the water because their fur does not insulate well when it’s",
"food he stored on the ark from being eaten by rats. In reply,",
"a tabby. Legend says that tabby cats have an “M” for Mohammed on",
"(20 meters), due largely to their “righting reflex.” The eyes and balance organs",
"how a cat purrs. Most veterinarians believe that a cat purrs by vibrating",
"used to get a cat’s attention. As a slang word for the female",
"A cat’s hearing is better than a dog’s. And a cat can hear",
"historically associated with cats.\", \"(46) The smallest wildcat today is the Black-footed cat.",
"a wider peripheral view. It’s worse because they don’t see color as well",
"lbs (1.2 kg).\", \"(47) On average, cats spend 2/3 of every day sleeping.",
"cat and the Siamese cat.\", \"(34) The smallest pedigreed cat is a Singapura,",
"pisica and the root of secondary words in Lithuanian (puz) and Low German",
"that a cat will smother a sleeping baby or suck out the child’s",
"the brain go to mostly the right eye and the nerves from the",
"import telegram import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with",
"Romanian term pisica and the root of secondary words in Lithuanian (puz) and",
"average cat weighs.\", \"(35) Some cats have survived falls of over 65 feet",
"if you want to, go ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [",
"group of animals that pet cats belong to emerged around 12 million years",
"cats give birth to a litter of between one and nine kittens. The",
"Mohammed loved cats and reportedly his favorite cat, Muezza, was a tabby. Legend",
"nearly twice as much as an average cat weighs.\", \"(35) Some cats have",
"The technical term for a cat’s hairball is a “bezoar”.\", \"(4) A group",
"than it is to a dog’s. Both humans and cats have identical regions",
"for emotions.\", \"(30) Many Egyptians worshipped the goddess Bast, who had a woman’s",
"\"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\",",
"🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\":",
"its way home is called “psi-traveling.” Experts think cats either use the angle",
"of the most expensive cats ever.\", \"(42) A cat usually has about 12",
"AttributeError: pass # these responses have several options to be selected at random",
"resistant.\", \"(40) The Egyptian Mau is probably the oldest breed of cat. In",
"in Britain and Australia, black cats are considered lucky.\", \"(33) The most popular",
"500 million domestic cats in the world, with approximately 40 recognized breeds.\", \"(9)",
"insulate well when it’s wet. The Turkish Van, however, is one cat that",
"“bezoar”.\", \"(4) A group of cats is called a “clowder”.\", \"(5) A cat",
"puus. Some scholars suggest that “puss” could be imitative of the hissing sound",
"level. Dogs and humans bob their heads up and down.\", \"(3) The technical",
"bob their heads up and down.\", \"(3) The technical term for a cat’s",
"singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses have several options to",
"furnishings.”\", \"(50) The ability of a cat to find its way home is",
"lucky.\", \"(33) The most popular pedigreed cat is the Persian cat, followed by",
"central Asia, its coat has a unique texture that makes it water resistant.\",",
"the Siamese cat.\", \"(34) The smallest pedigreed cat is a Singapura, which can",
"humans and cats have identical regions in their brains that are responsible for",
"that help keep out dirt direct sounds into the ear, and insulate the",
"would mourn by shaving off their eyebrows. They also held elaborate funerals during",
"brain go mostly to the left eye. This causes some double vision, which",
"that makes it water resistant.\", \"(40) The Egyptian Mau is probably the oldest",
"found in a 9,500-year-old grave on the Mediterranean island of Cyprus. This grave",
"can see in much dimmer light and they have a wider peripheral view.",
"Cinderella, the benevolent fairy godmother figure was a cat.\", \"(49) The little tufts",
"of the rat population, which exacerbated the effects of the Black Death.\", \"(12)",
"biologically more similar to a human brain than it is to a dog’s.",
"godmother figure was a cat.\", \"(49) The little tufts of hair in a",
"dictionary of trigger words with single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵",
"ancient Egyptians were the first to domesticate cats, the oldest known pet cat",
"rat population, which exacerbated the effects of the Black Death.\", \"(12) During the",
"first cat in space was a French cat named Felicette (a.k.a. “Astrocat”) In",
"auf Deutsch!\", \"Oh, and remember, next Friday is Swedish luggage day, so, you",
"humans do. Scientists believe grass appears red to cats.\", \"(44) Spanish-Jewish folklore recounts",
"random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single 1:1 reply",
"called a “clowder”.\", \"(5) A cat can’t climb head first down a tree",
"is one cat that likes swimming. Bred in central Asia, its coat has",
"to an explosion of the rat population, which exacerbated the effects of the",
"an explosion of the rat population, which exacerbated the effects of the Black",
"has about 12 whiskers on each side of its face.\", \"(43) A cat’s",
"or wild cat.\", \"(15) The term “puss” is the root of the principal",
"reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\",",
"63 million dogs. Over 30% of households in North America own a cat.\",",
"to the left eye. This causes some double vision, which the cat tries",
"the nerves from the left side of the brain go to mostly the",
"members would mourn by shaving off their eyebrows. They also held elaborate funerals",
"ancestor of the modern cat lived about 30 million years ago. Scientists called",
"out popped a cat.\", \"(19) A cat’s hearing is better than a dog’s.",
"cat into outer space. Electrodes implanted in her brains sent neurological signals back",
"of the hissing sound used to get a cat’s attention. As a slang",
"coat has a unique texture that makes it water resistant.\", \"(40) The Egyptian",
"face.\", \"(43) A cat’s eyesight is both better and worse than humans. It",
"can weigh 25 lbs (11.3 kg), or nearly twice as much as an",
"cat’s eyesight is both better and worse than humans. It is better because",
"responses have several options to be selected at random for trigger in multireplydict:",
"over a short distance.\", \"(21) A cat rubs against people not only to",
"of cat food. The largest pedigreed cats are Maine Coon cats, which can",
"\"(1) Unlike dogs, cats do not have a sweet tooth. Scientists believe this",
"“puss” could be imitative of the hissing sound used to get a cat’s",
"largest pedigreed cats are Maine Coon cats, which can weigh 25 lbs (11.3",
"a cat chases its prey, it keeps its head level. Dogs and humans",
"eaten in Asia.\", \"(8) There are more than 500 million domestic cats in",
"was punishable by death. Phoenician traders eventually succeeded in smuggling felines, which they",
"Egyptians worshipped the goddess Bast, who had a woman’s body and a cat’s",
"cat died in ancient Egypt, family members would mourn by shaving off their",
"\"Mmm... yeah... the pack for the back.\", \"I like turtles.\", \"I like pie.\",",
"head first down a tree because every claw on a cat’s paw points",
"Smuggling a cat out of ancient Egypt was punishable by death. Phoenician traders",
"“cat.”\", \"(41) The first commercially cloned pet was a cat named “<NAME>”. He",
"for fertilizer.\", \"(25) Most cats give birth to a litter of between one",
"can’t climb head first down a tree because every claw on a cat’s",
"belong to emerged around 12 million years ago.\", \"(28) The biggest wildcat today",
"This causes some double vision, which the cat tries to correct by “crossing”",
"are unsure exactly how a cat purrs. Most veterinarians believe that a cat",
"\"(34) The smallest pedigreed cat is a Singapura, which can weigh just 4",
"would often rest his hand on the cat’s head.\", \"(32) While many parts",
"first commercially cloned pet was a cat named “<NAME>”. He cost his owner",
"cats from church towers.\", \"(13) The first cat in space was a French",
"fairy godmother figure was a cat.\", \"(49) The little tufts of hair in",
"can weigh as little as 2.5 lbs (1.2 kg).\", \"(47) On average, cats",
"trigger words with multiple random responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\",",
"was recently found in a 9,500-year-old grave on the Mediterranean island of Cyprus.",
"word “tabby” comes from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got their",
"in England and the U.S. for fertilizer.\", \"(25) Most cats give birth to",
"Bred in central Asia, its coat has a unique texture that makes it",
"carry the cat’s scent.\", \"(22) Researchers are unsure exactly how a cat purrs.",
"vampire cat, sucking the blood from sleeping babies. This may be the root",
"identical regions in their brains that are responsible for emotions.\", \"(30) Many Egyptians",
"= { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the",
"households in North America own a cat.\", \"(18) According to Hebrew legend, Noah",
"eyesight is both better and worse than humans. It is better because cats",
"red to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first wife, Lilith, became",
"cat” in Greek. The group of animals that pet cats belong to emerged",
"his owner $50,000, making him one of the most expensive cats ever.\", \"(42)",
"depicting cats by 4,000 years or more.\", \"(11) During the time of the",
"with approximately 40 recognized breeds.\", \"(9) Approximately 24 cat skins can make a",
"correct by “crossing” its eyes.\", \"(37) Researchers believe the word “tabby” comes from",
"have an “M” for Mohammed on top of their heads because Mohammad would",
"(a.k.a. “Astrocat”) In 1963, France blasted the cat into outer space. Electrodes implanted",
"head level. Dogs and humans bob their heads up and down.\", \"(3) The",
"go ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ],",
"left eye. This causes some double vision, which the cat tries to correct",
"North America own a cat.\", \"(18) According to Hebrew legend, Noah prayed to",
"\"(27) The earliest ancestor of the modern cat lived about 30 million years",
"There are more than 500 million domestic cats in the world, with approximately",
"people celebrated by tossing cats from church towers.\", \"(13) The first cat in",
"Persian cat, followed by the Maine Coon cat and the Siamese cat.\", \"(34)",
"a key taste receptor.\", \"(2) When a cat chases its prey, it keeps",
"eyes and balance organs in the inner ear tell it where it is",
"and the nerves from the right side of the brain go mostly to",
"France blasted the cat into outer space. Electrodes implanted in her brains sent",
"cats in the U.S. annually.\", \"(17) Cats are North America’s most popular pets:",
"bonfires. On holy days, people celebrated by tossing cats from church towers.\", \"(13)",
"the female pudenda, it could be associated with the connotation of a cat",
"him one of the most expensive cats ever.\", \"(42) A cat usually has",
"of the modern cat lived about 30 million years ago. Scientists called it",
"of words associated with cat (catt, cath, chat, katze) stem from the Latin",
"sacks and toss the cats into bonfires. On holy days, people celebrated by",
"is biologically more similar to a human brain than it is to a",
"(11.3 kg), or nearly twice as much as an average cat weighs.\", \"(35)",
"a cat.\", \"(18) According to Hebrew legend, Noah prayed to God for help",
"cats without a tail have this ability.\", \"(36) Some Siamese cats appear cross-eyed",
"humans. It is better because cats can see in much dimmer light and",
"\"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs,",
"responsible for emotions.\", \"(30) Many Egyptians worshipped the goddess Bast, who had a",
"U.S. annually.\", \"(17) Cats are North America’s most popular pets: there are 73",
"pedigreed cat is a Singapura, which can weigh just 4 lbs (1.8 kg),",
"words with single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵",
"Hebrew legend, Noah prayed to God for help protecting all the food he",
"thought that the ancient Egyptians were the first to domesticate cats, the oldest",
"America’s most popular pets: there are 73 million cats compared to 63 million",
"the breed is so ancient that its name is the Egyptian word for",
"early Egyptian art depicting cats by 4,000 years or more.\", \"(11) During the",
"\"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\", \"I like turtles.\",",
"mapped responses for trigger in singlereplydict: try: if trigger in messagetext.lower(): replytext =",
"led to an explosion of the rat population, which exacerbated the effects of",
"is called a “clowder”.\", \"(5) A cat can’t climb head first down a",
"over Europe would stuff them into sacks and toss the cats into bonfires.",
"the cat’s scent.\", \"(22) Researchers are unsure exactly how a cat purrs. Most",
"in space was a French cat named Felicette (a.k.a. “Astrocat”) In 1963, France",
"so, you know, if you want to, go ahead and wear a bäckpäck.\",",
"on a cat’s paw points the same way. To get down from a",
"scholars suggest that “puss” could be imitative of the hissing sound used to",
"“righting reflex.” The eyes and balance organs in the inner ear tell it",
"sorcery historically associated with cats.\", \"(46) The smallest wildcat today is the Black-footed",
"responses multireplydict = { \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack",
"a family cat died in ancient Egypt, family members would mourn by shaving",
"also to mark out its territory with scent glands around its face. The",
"fertilizer.\", \"(25) Most cats give birth to a litter of between one and",
"an average cat weighs.\", \"(35) Some cats have survived falls of over 65",
"imitative of the hissing sound used to get a cat’s attention. As a",
"Egyptian word for “cat.”\", \"(41) The first commercially cloned pet was a cat",
"comes from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got their name because",
"cat in space was a French cat named Felicette (a.k.a. “Astrocat”) In 1963,",
"are responsible for emotions.\", \"(30) Many Egyptians worshipped the goddess Bast, who had",
"to be used by farmers in England and the U.S. for fertilizer.\", \"(25)",
"the trip.\", \"(14) The group of words associated with cat (catt, cath, chat,",
"As a slang word for the female pudenda, it could be associated with",
"in their brains that are responsible for emotions.\", \"(30) Many Egyptians worshipped the",
"dimmer light and they have a wider peripheral view. It’s worse because they",
"\"(5) A cat can’t climb head first down a tree because every claw",
"into outer space. Electrodes implanted in her brains sent neurological signals back to",
"🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } #",
"<gh_stars>1-10 import os import telegram import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of",
"on top of their heads because Mohammad would often rest his hand on",
"cat, Muezza, was a tabby. Legend says that tabby cats have an “M”",
"population, which exacerbated the effects of the Black Death.\", \"(12) During the Middle",
"warm, and fuzzy.\", \"(16) Approximately 40,000 people are bitten by cats in the",
"is the Egyptian word for “cat.”\", \"(41) The first commercially cloned pet was",
"The group of animals that pet cats belong to emerged around 12 million",
"both better and worse than humans. It is better because cats can see",
"the Black Death.\", \"(12) During the Middle Ages, cats were associated with withcraft,",
"first to domesticate cats, the oldest known pet cat was recently found in",
"about 12 whiskers on each side of its face.\", \"(43) A cat’s eyesight",
"The smallest wildcat today is the Black-footed cat. The females are less than",
"in the U.S. annually.\", \"(17) Cats are North America’s most popular pets: there",
"the rat population, which exacerbated the effects of the Black Death.\", \"(12) During",
"in North America own a cat.\", \"(18) According to Hebrew legend, Noah prayed",
"loved cats and reportedly his favorite cat, Muezza, was a tabby. Legend says",
"(1.8 kg), or about five large cans of cat food. The largest pedigreed",
"out the child’s breath.\", \"(45) Perhaps the most famous comic cat is the",
"12 whiskers on each side of its face.\", \"(43) A cat’s eyesight is",
"the famous wavy patterns in the silk produced in this city.\", \"(38) A",
"double vision, which the cat tries to correct by “crossing” its eyes.\", \"(37)",
"more.\", \"(11) During the time of the Spanish Inquisition, Pope Innocent VIII condemned",
"in the Romanian term pisica and the root of secondary words in Lithuanian",
"cats and reportedly his favorite cat, Muezza, was a tabby. Legend says that",
"Cheshire Cat in Lewis Carroll’s Alice in Wonderland. With the ability to disappear,",
"The Turkish Van, however, is one cat that likes swimming. Bred in central",
"from sleeping babies. This may be the root of the superstition that a",
"which means “first cat” in Greek. The group of animals that pet cats",
"litter of between one and nine kittens. The largest known litter ever produced",
"And a cat can hear high-frequency sounds up to two octaves higher than",
"\"(31) Mohammed loved cats and reportedly his favorite cat, Muezza, was a tabby.",
"around its face. The tail area and paws also carry the cat’s scent.\",",
"it’s wet. The Turkish Van, however, is one cat that likes swimming. Bred",
"approximately 31 mph (49 km) over a short distance.\", \"(21) A cat rubs",
"words associated with cat (catt, cath, chat, katze) stem from the Latin catus,",
"$50,000, making him one of the most expensive cats ever.\", \"(42) A cat",
"], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts",
"high-frequency sounds up to two octaves higher than a human.\", \"(20) A cat",
"usually has about 12 whiskers on each side of its face.\", \"(43) A",
"{ \"backpack\": [ \"https://media.giphy.com/media/xUA7aXRRUlmqhoG7q8/giphy.gif\", \"https://media.giphy.com/media/2DjXJ5UmrqYPm/giphy.gif\", \"https://media.giphy.com/media/E1MTLQN0vFac8/giphy.gif\", \"Mmm... yeah... the pack for the back.\",",
"the larynx opens and closes the air passage about 25 times per second.\",",
"beat their breasts. The cat was embalmed with a sculpted wooden mask and",
"cath, chat, katze) stem from the Latin catus, meaning domestic cat, as opposed",
"survived falls of over 65 feet (20 meters), due largely to their “righting",
"purrs. Most veterinarians believe that a cat purrs by vibrating vocal folds deep",
"a pet cemetery with tiny mummies of mice.\", \"(24) In 1888, more than",
"rich people in Athens and other important cities.\", \"(27) The earliest ancestor of",
"the Persian cat, followed by the Maine Coon cat and the Siamese cat.\",",
"\"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words with multiple random",
"text=replytext) except AttributeError: pass # these responses have several options to be selected",
"stripped of their wrappings and carted off to be used by farmers in",
"about 30 million years ago. Scientists called it the Proailurus, which means “first",
"because they don’t see color as well as humans do. Scientists believe grass",
"its face.\", \"(43) A cat’s eyesight is both better and worse than humans.",
"\"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\",",
"exacerbated the effects of the Black Death.\", \"(12) During the Middle Ages, cats",
"the throat. To do this, a muscle in the larynx opens and closes",
"feles, or wild cat.\", \"(15) The term “puss” is the root of the",
"appear cross-eyed because the nerves from the left side of the brain go",
"produced was 19 kittens, of which 15 survived.\", \"(26) Smuggling a cat out",
"Most cats give birth to a litter of between one and nine kittens.",
"\"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1)",
"life.\", \"(48) In the original Italian version of Cinderella, the benevolent fairy godmother",
"Researchers believe the word “tabby” comes from Attabiyah, a neighborhood in Baghdad, Iraq.",
"the Latin catus, meaning domestic cat, as opposed to feles, or wild cat.\",",
"with cats.\", \"(46) The smallest wildcat today is the Black-footed cat. The females",
"(317 kg).\", \"(29) A cat’s brain is biologically more similar to a human",
"have this ability.\", \"(36) Some Siamese cats appear cross-eyed because the nerves from",
"Europe would stuff them into sacks and toss the cats into bonfires. On",
"4 lbs (1.8 kg), or about five large cans of cat food. The",
"associated with cats.\", \"(46) The smallest wildcat today is the Black-footed cat. The",
"︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\":",
"the tiny mummy was placed in the family tomb or in a pet",
"kg), or about five large cans of cat food. The largest pedigreed cats",
"of Europe and North America consider the black cat a sign of bad",
"the root of secondary words in Lithuanian (puz) and Low German puus. Some",
"Asia.\", \"(8) There are more than 500 million domestic cats in the world,",
"webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext",
"as opposed to feles, or wild cat.\", \"(15) The term “puss” is the",
"\"(33) The most popular pedigreed cat is the Persian cat, followed by the",
"help keep out dirt direct sounds into the ear, and insulate the ears",
"up to five times its own height in a single bound.\", \"(39) Cats",
"Ages, cats were associated with withcraft, and on St. John’s Day, people all",
"kg).\", \"(47) On average, cats spend 2/3 of every day sleeping. That means",
"of the Spanish Inquisition, Pope Innocent VIII condemned cats as evil and thousands",
"female pudenda, it could be associated with the connotation of a cat being",
"them into sacks and toss the cats into bonfires. On holy days, people",
"cat.\", \"(49) The little tufts of hair in a cat’s ear that help",
"most expensive cats ever.\", \"(42) A cat usually has about 12 whiskers on",
"cat’s hairball is a “bezoar”.\", \"(4) A group of cats is called a",
"associated with the connotation of a cat being soft, warm, and fuzzy.\", \"(16)",
"\"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source",
"\"(38) A cat can jump up to five times its own height in",
"peripheral view. It’s worse because they don’t see color as well as humans",
"cats, the oldest known pet cat was recently found in a 9,500-year-old grave",
"must back down.\", \"(6) Cats make about 100 different sounds. Dogs make only",
"in Lewis Carroll’s Alice in Wonderland. With the ability to disappear, this mysterious",
"back to Earth. She survived the trip.\", \"(14) The group of words associated",
"resembled the famous wavy patterns in the silk produced in this city.\", \"(38)",
"tiny mummies of mice.\", \"(24) In 1888, more than 300,000 mummified cats were",
"better than a dog’s. And a cat can hear high-frequency sounds up to",
"], } def webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id",
"expensive cats ever.\", \"(42) A cat usually has about 12 whiskers on each",
"kittens. The largest known litter ever produced was 19 kittens, of which 15",
"blasted the cat into outer space. Electrodes implanted in her brains sent neurological",
"Phoenician traders eventually succeeded in smuggling felines, which they sold to rich people",
"mysterious character embodies the magic and sorcery historically associated with cats.\", \"(46) The",
"been awake for only three years of its life.\", \"(48) In the original",
"towers.\", \"(13) The first cat in space was a French cat named Felicette",
"in a single bound.\", \"(39) Cats hate the water because their fur does",
"are called “ear furnishings.”\", \"(50) The ability of a cat to find its",
"French cat named Felicette (a.k.a. “Astrocat”) In 1963, France blasted the cat into",
"coat.\", \"(10) While it is commonly thought that the ancient Egyptians were the",
"claw on a cat’s paw points the same way. To get down from",
"the Egyptian word for “cat.”\", \"(41) The first commercially cloned pet was a",
"the ears are called “ear furnishings.”\", \"(50) The ability of a cat to",
"= update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1 mapped responses for trigger in",
"“psi-traveling.” Experts think cats either use the angle of the sunlight to find",
"Egypt was punishable by death. Phoenician traders eventually succeeded in smuggling felines, which",
"has been awake for only three years of its life.\", \"(48) In the",
"black cats are considered lucky.\", \"(33) The most popular pedigreed cat is the",
"\"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike",
"While it is commonly thought that the ancient Egyptians were the first to",
"1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵",
"\"(17) Cats are North America’s most popular pets: there are 73 million cats",
"sleeping babies. This may be the root of the superstition that a cat",
"of ancient Egypt was punishable by death. Phoenician traders eventually succeeded in smuggling",
"unique texture that makes it water resistant.\", \"(40) The Egyptian Mau is probably",
"\\\\(°□°)/ ︵ ┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\",",
"emotions.\", \"(30) Many Egyptians worshipped the goddess Bast, who had a woman’s body",
"vision, which the cat tries to correct by “crossing” its eyes.\", \"(37) Researchers",
"Van, however, is one cat that likes swimming. Bred in central Asia, its",
"see color as well as humans do. Scientists believe grass appears red to",
"at a top speed of approximately 31 mph (49 km) over a short",
"(1.2 kg).\", \"(47) On average, cats spend 2/3 of every day sleeping. That",
"the Spanish Inquisition, Pope Innocent VIII condemned cats as evil and thousands of",
"stem from the Latin catus, meaning domestic cat, as opposed to feles, or",
"kg), or nearly twice as much as an average cat weighs.\", \"(35) Some",
"females are less than 20 inches (50 cm) long and can weigh as",
"Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got their name because their striped",
"lbs (11.3 kg), or nearly twice as much as an average cat weighs.\",",
"\"(25) Most cats give birth to a litter of between one and nine",
"Most veterinarians believe that a cat purrs by vibrating vocal folds deep in",
"word for the female pudenda, it could be associated with the connotation of",
"Tiger. It can be more than 12 feet (3.6 m) long (about the",
"it the Proailurus, which means “first cat” in Greek. The group of animals",
"telegram import random bot = telegram.Bot(token=os.environ[\"TELEGRAM_TOKEN\"]) # dictionary of trigger words with single",
"to correct by “crossing” its eyes.\", \"(37) Researchers believe the word “tabby” comes",
"to be affectionate but also to mark out its territory with scent glands",
"their breasts. The cat was embalmed with a sculpted wooden mask and the",
"dogs. Over 30% of households in North America own a cat.\", \"(18) According",
"its coat has a unique texture that makes it water resistant.\", \"(40) The",
"of approximately 31 mph (49 km) over a short distance.\", \"(21) A cat",
"today is the Black-footed cat. The females are less than 20 inches (50",
"back.\", \"I like turtles.\", \"I like pie.\", \"Das ist ein rucksack auf Deutsch!\",",
"to Earth. She survived the trip.\", \"(14) The group of words associated with",
"people not only to be affectionate but also to mark out its territory",
"the most expensive cats ever.\", \"(42) A cat usually has about 12 whiskers",
"out of ancient Egypt was punishable by death. Phoenician traders eventually succeeded in",
"up and down.\", \"(3) The technical term for a cat’s hairball is a",
"these responses have several options to be selected at random for trigger in",
"farmers in England and the U.S. for fertilizer.\", \"(25) Most cats give birth",
"of the brain go mostly to the left eye. This causes some double",
"the lion sneeze, and out popped a cat.\", \"(19) A cat’s hearing is",
"than 300,000 mummified cats were found an Egyptian cemetery. They were stripped of",
"\"(14) The group of words associated with cat (catt, cath, chat, katze) stem",
"of the superstition that a cat will smother a sleeping baby or suck",
"She survived the trip.\", \"(14) The group of words associated with cat (catt,",
"human brain than it is to a dog’s. Both humans and cats have",
"body and a cat’s head.\", \"(31) Mohammed loved cats and reportedly his favorite",
"turtles.\", \"I like pie.\", \"Das ist ein rucksack auf Deutsch!\", \"Oh, and remember,",
"to domesticate cats, the oldest known pet cat was recently found in a",
"to rich people in Athens and other important cities.\", \"(27) The earliest ancestor",
"oldest known pet cat was recently found in a 9,500-year-old grave on the",
"cat to find its way home is called “psi-traveling.” Experts think cats either",
"in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses",
"cat will smother a sleeping baby or suck out the child’s breath.\", \"(45)",
"\"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵ 🍕\", \"hotdogflip\": \"(╯°□°)╯︵ 🌭\", \"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\":",
"years or more.\", \"(11) During the time of the Spanish Inquisition, Pope Innocent",
"by the Maine Coon cat and the Siamese cat.\", \"(34) The smallest pedigreed",
"https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do not have a sweet tooth.",
"= singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses have several options",
"breed of cat. In fact, the breed is so ancient that its name",
"cat tries to correct by “crossing” its eyes.\", \"(37) Researchers believe the word",
"wildcat today is the Black-footed cat. The females are less than 20 inches",
"the Maine Coon cat and the Siamese cat.\", \"(34) The smallest pedigreed cat",
"which they drank wine and beat their breasts. The cat was embalmed with",
"had a woman’s body and a cat’s head.\", \"(31) Mohammed loved cats and",
"\"(50) The ability of a cat to find its way home is called",
"the hissing sound used to get a cat’s attention. As a slang word",
"word for “cat.”\", \"(41) The first commercially cloned pet was a cat named",
"closes the air passage about 25 times per second.\", \"(23) When a family",
"make a coat.\", \"(10) While it is commonly thought that the ancient Egyptians",
"if trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass return",
"small car) and weigh up to 700 pounds (317 kg).\", \"(29) A cat’s",
"Siberian Tiger. It can be more than 12 feet (3.6 m) long (about",
"wavy patterns in the silk produced in this city.\", \"(38) A cat can",
"holy days, people celebrated by tossing cats from church towers.\", \"(13) The first",
"“clowder”.\", \"(5) A cat can’t climb head first down a tree because every",
"and the U.S. for fertilizer.\", \"(25) Most cats give birth to a litter",
"favorite cat, Muezza, was a tabby. Legend says that tabby cats have an",
"America own a cat.\", \"(18) According to Hebrew legend, Noah prayed to God",
"cat out of ancient Egypt was punishable by death. Phoenician traders eventually succeeded",
"will smother a sleeping baby or suck out the child’s breath.\", \"(45) Perhaps",
"\"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\", \"pastryparty\": \"🍞🥖🥐🥯🥨🥞🍩🍪🍰🧁\", \"doubleflip\": \"┻━┻︵ \\\\(°□°)/",
"ever.\", \"(42) A cat usually has about 12 whiskers on each side of",
"rats. In reply, God made the lion sneeze, and out popped a cat.\",",
"today is the Siberian Tiger. It can be more than 12 feet (3.6",
"most popular pedigreed cat is the Persian cat, followed by the Maine Coon",
"wine and beat their breasts. The cat was embalmed with a sculpted wooden",
"tooth. Scientists believe this is due to a mutation in a key taste",
"\"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger",
"you know, if you want to, go ahead and wear a bäckpäck.\", ],",
"are eaten in Asia.\", \"(8) There are more than 500 million domestic cats",
"during which they drank wine and beat their breasts. The cat was embalmed",
"the word “tabby” comes from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got",
"12 million years ago.\", \"(28) The biggest wildcat today is the Siberian Tiger.",
"ability of a cat to find its way home is called “psi-traveling.” Experts",
"muscle in the larynx opens and closes the air passage about 25 times",
"dogs, cats do not have a sweet tooth. Scientists believe this is due",
"[ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\",",
"the Siberian Tiger. It can be more than 12 feet (3.6 m) long",
"comic cat is the Cheshire Cat in Lewis Carroll’s Alice in Wonderland. With",
"cats belong to emerged around 12 million years ago.\", \"(28) The biggest wildcat",
"than 500 million domestic cats in the world, with approximately 40 recognized breeds.\",",
"sounds into the ear, and insulate the ears are called “ear furnishings.”\", \"(50)",
"were found an Egyptian cemetery. They were stripped of their wrappings and carted",
"The ability of a cat to find its way home is called “psi-traveling.”",
"around 12 million years ago.\", \"(28) The biggest wildcat today is the Siberian",
"believe grass appears red to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first",
"Spanish Inquisition, Pope Innocent VIII condemned cats as evil and thousands of cats",
"in smuggling felines, which they sold to rich people in Athens and other",
"from Attabiyah, a neighborhood in Baghdad, Iraq. Tabbies got their name because their",
"because cats can see in much dimmer light and they have a wider",
"cross-eyed because the nerves from the left side of the brain go to",
"a 9,500-year-old grave on the Mediterranean island of Cyprus. This grave predates early",
"texture that makes it water resistant.\", \"(40) The Egyptian Mau is probably the",
"of a cat to find its way home is called “psi-traveling.” Experts think",
"if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass #",
"tail area and paws also carry the cat’s scent.\", \"(22) Researchers are unsure",
"that the ancient Egyptians were the first to domesticate cats, the oldest known",
"Researchers are unsure exactly how a cat purrs. Most veterinarians believe that a",
"dirt direct sounds into the ear, and insulate the ears are called “ear",
"that its name is the Egyptian word for “cat.”\", \"(41) The first commercially",
"wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\",",
"by shaving off their eyebrows. They also held elaborate funerals during which they",
"brains sent neurological signals back to Earth. She survived the trip.\", \"(14) The",
"the blood from sleeping babies. This may be the root of the superstition",
"a tree because every claw on a cat’s paw points the same way.",
"from church towers.\", \"(13) The first cat in space was a French cat",
"Australia, black cats are considered lucky.\", \"(33) The most popular pedigreed cat is",
"a single bound.\", \"(39) Cats hate the water because their fur does not",
"oldest breed of cat. In fact, the breed is so ancient that its",
"When a cat chases its prey, it keeps its head level. Dogs and",
"for a cat’s hairball is a “bezoar”.\", \"(4) A group of cats is",
"bitten by cats in the U.S. annually.\", \"(17) Cats are North America’s most",
"attention. As a slang word for the female pudenda, it could be associated",
"size of a small car) and weigh up to 700 pounds (317 kg).\",",
"a cat.\", \"(19) A cat’s hearing is better than a dog’s. And a",
"want to, go ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\",",
"chases its prey, it keeps its head level. Dogs and humans bob their",
"31 mph (49 km) over a short distance.\", \"(21) A cat rubs against",
"you want to, go ahead and wear a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\",",
"on the Mediterranean island of Cyprus. This grave predates early Egyptian art depicting",
"the original Italian version of Cinderella, the benevolent fairy godmother figure was a",
"of which 15 survived.\", \"(26) Smuggling a cat out of ancient Egypt was",
"by vibrating vocal folds deep in the throat. To do this, a muscle",
"the inner ear tell it where it is in space so the cat",
"the Black-footed cat. The females are less than 20 inches (50 cm) long",
"that a cat purrs by vibrating vocal folds deep in the throat. To",
"VIII condemned cats as evil and thousands of cats were burned. Unfortunately, the",
"in a key taste receptor.\", \"(2) When a cat chases its prey, it",
"prey, it keeps its head level. Dogs and humans bob their heads up",
"do this, a muscle in the larynx opens and closes the air passage",
"cat being soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people are bitten by",
"as much as an average cat weighs.\", \"(35) Some cats have survived falls",
"\"ಠ_ಠ\", \"octodisco\": \"🎶🐙🎶\", \"octodance\": \"🎶🐙🎶\", } # dictionary of trigger words with multiple",
"rubs against people not only to be affectionate but also to mark out",
"to a human brain than it is to a dog’s. Both humans and",
"hair in a cat’s ear that help keep out dirt direct sounds into",
"it could be associated with the connotation of a cat being soft, warm,",
"cat’s attention. As a slang word for the female pudenda, it could be",
"that “puss” could be imitative of the hissing sound used to get a",
"Egyptians were the first to domesticate cats, the oldest known pet cat was",
"or in a pet cemetery with tiny mummies of mice.\", \"(24) In 1888,",
"their brains that act as compasses.\", ], } def webhook(request): if request.method ==",
"find their way or that cats have magnetized cells in their brains that",
"weigh as little as 2.5 lbs (1.2 kg).\", \"(47) On average, cats spend",
"\"(43) A cat’s eyesight is both better and worse than humans. It is",
"\"(2) When a cat chases its prey, it keeps its head level. Dogs",
"tossing cats from church towers.\", \"(13) The first cat in space was a",
"def webhook(request): if request.method == \"POST\": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id",
"fact, the breed is so ancient that its name is the Egyptian word",
"days, people celebrated by tossing cats from church towers.\", \"(13) The first cat",
"A group of cats is called a “clowder”.\", \"(5) A cat can’t climb",
"mourn by shaving off their eyebrows. They also held elaborate funerals during which",
"chat, katze) stem from the Latin catus, meaning domestic cat, as opposed to",
"\"(12) During the Middle Ages, cats were associated with withcraft, and on St.",
"\"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\", \"http://rs367.pbsrc.com/albums/oo112/Aim_fire/sdgfasfdgd.jpg~c200\", \"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\":",
"was placed in the family tomb or in a pet cemetery with tiny",
"\"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\", \"octodisco\":",
"in the world, with approximately 40 recognized breeds.\", \"(9) Approximately 24 cat skins",
"to find their way or that cats have magnetized cells in their brains",
"famous comic cat is the Cheshire Cat in Lewis Carroll’s Alice in Wonderland.",
"withcraft, and on St. John’s Day, people all over Europe would stuff them",
"a cat out of ancient Egypt was punishable by death. Phoenician traders eventually",
"of cats were burned. Unfortunately, the widespread killing of cats led to an",
"and fuzzy.\", \"(16) Approximately 40,000 people are bitten by cats in the U.S.",
"in a pet cemetery with tiny mummies of mice.\", \"(24) In 1888, more",
"# direct 1:1 mapped responses for trigger in singlereplydict: try: if trigger in",
"\"(9) Approximately 24 cat skins can make a coat.\", \"(10) While it is",
"their wrappings and carted off to be used by farmers in England and",
"U.S. for fertilizer.\", \"(25) Most cats give birth to a litter of between",
"it is commonly thought that the ancient Egyptians were the first to domesticate",
"God for help protecting all the food he stored on the ark from",
"cat has been awake for only three years of its life.\", \"(48) In",
"to their “righting reflex.” The eyes and balance organs in the inner ear",
"in Wonderland. With the ability to disappear, this mysterious character embodies the magic",
"inner ear tell it where it is in space so the cat can",
"in Greek. The group of animals that pet cats belong to emerged around",
"weigh just 4 lbs (1.8 kg), or about five large cans of cat",
"and they have a wider peripheral view. It’s worse because they don’t see",
"head.\", \"(31) Mohammed loved cats and reportedly his favorite cat, Muezza, was a",
"which can weigh 25 lbs (11.3 kg), or nearly twice as much as",
"scent glands around its face. The tail area and paws also carry the",
"much as an average cat weighs.\", \"(35) Some cats have survived falls of",
"cat is the Cheshire Cat in Lewis Carroll’s Alice in Wonderland. With the",
"the principal word for “cat” in the Romanian term pisica and the root",
"The females are less than 20 inches (50 cm) long and can weigh",
"group of words associated with cat (catt, cath, chat, katze) stem from the",
"smuggling felines, which they sold to rich people in Athens and other important",
"of the principal word for “cat” in the Romanian term pisica and the",
"nerves from the right side of the brain go mostly to the left",
"a cat must back down.\", \"(6) Cats make about 100 different sounds. Dogs",
"update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.effective_message.chat.id messagetext = update.effective_message.text # direct 1:1",
"Lithuanian (puz) and Low German puus. Some scholars suggest that “puss” could be",
"named “<NAME>”. He cost his owner $50,000, making him one of the most",
"means “first cat” in Greek. The group of animals that pet cats belong",
"commercially cloned pet was a cat named “<NAME>”. He cost his owner $50,000,",
"Every year, nearly four million cats are eaten in Asia.\", \"(8) There are",
"source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats do not have a sweet",
"because their striped coats resembled the famous wavy patterns in the silk produced",
"a cat’s paw points the same way. To get down from a tree,",
"by death. Phoenician traders eventually succeeded in smuggling felines, which they sold to",
"brain is biologically more similar to a human brain than it is to",
"in this city.\", \"(38) A cat can jump up to five times its",
"ears are called “ear furnishings.”\", \"(50) The ability of a cat to find",
"is so ancient that its name is the Egyptian word for “cat.”\", \"(41)",
"probably the oldest breed of cat. In fact, the breed is so ancient",
"used by farmers in England and the U.S. for fertilizer.\", \"(25) Most cats",
"\"(28) The biggest wildcat today is the Siberian Tiger. It can be more",
"bad luck, in Britain and Australia, black cats are considered lucky.\", \"(33) The",
"feet (3.6 m) long (about the size of a small car) and weigh",
"\"(29) A cat’s brain is biologically more similar to a human brain than",
"organs in the inner ear tell it where it is in space so",
"The first cat in space was a French cat named Felicette (a.k.a. “Astrocat”)",
"is better because cats can see in much dimmer light and they have",
"to a mutation in a key taste receptor.\", \"(2) When a cat chases",
"a cat to find its way home is called “psi-traveling.” Experts think cats",
"feet (20 meters), due largely to their “righting reflex.” The eyes and balance",
"are North America’s most popular pets: there are 73 million cats compared to",
"speed of approximately 31 mph (49 km) over a short distance.\", \"(21) A",
"mostly to the left eye. This causes some double vision, which the cat",
"domestic cats in the world, with approximately 40 recognized breeds.\", \"(9) Approximately 24",
"reportedly his favorite cat, Muezza, was a tabby. Legend says that tabby cats",
"many parts of Europe and North America consider the black cat a sign",
"followed by the Maine Coon cat and the Siamese cat.\", \"(34) The smallest",
"a bäckpäck.\", ], \"dumpsterfire\": [ \"https://media.giphy.com/media/QLyhWVTvAHbAbAdWcp/giphy.gif\", \"https://media.giphy.com/media/134vVkHV9wQtaw/giphy.gif\", \"https://media.giphy.com/media/FqtWrearu5vb2/giphy.gif\", ], \"chika\": [ \"https://media1.tenor.com/images/38b0f21d0e76dec2ff58d19e37fcc716/tenor.gif?itemid=4484736\", \"https://1funny.com/wp-content/uploads/2009/07/diabeetus-cat.jpg\",",
"were associated with withcraft, and on St. John’s Day, people all over Europe",
"Cats are North America’s most popular pets: there are 73 million cats compared",
"to Hebrew legend, Noah prayed to God for help protecting all the food",
"family tomb or in a pet cemetery with tiny mummies of mice.\", \"(24)",
"cloned pet was a cat named “<NAME>”. He cost his owner $50,000, making",
"they don’t see color as well as humans do. Scientists believe grass appears",
"spend 2/3 of every day sleeping. That means a nine-year-old cat has been",
"due to a mutation in a key taste receptor.\", \"(2) When a cat",
"exactly how a cat purrs. Most veterinarians believe that a cat purrs by",
"million years ago.\", \"(28) The biggest wildcat today is the Siberian Tiger. It",
"and out popped a cat.\", \"(19) A cat’s hearing is better than a",
"heads up and down.\", \"(3) The technical term for a cat’s hairball is",
"Cyprus. This grave predates early Egyptian art depicting cats by 4,000 years or",
"update.effective_message.text # direct 1:1 mapped responses for trigger in singlereplydict: try: if trigger",
"be affectionate but also to mark out its territory with scent glands around",
"worse because they don’t see color as well as humans do. Scientists believe",
"the cat can land on its feet. Even cats without a tail have",
"The Egyptian Mau is probably the oldest breed of cat. In fact, the",
"awake for only three years of its life.\", \"(48) In the original Italian",
"to 63 million dogs. Over 30% of households in North America own a",
"does not insulate well when it’s wet. The Turkish Van, however, is one",
"elaborate funerals during which they drank wine and beat their breasts. The cat",
"vocal folds deep in the throat. To do this, a muscle in the",
"for “cat.”\", \"(41) The first commercially cloned pet was a cat named “<NAME>”.",
"suck out the child’s breath.\", \"(45) Perhaps the most famous comic cat is",
"out its territory with scent glands around its face. The tail area and",
"grave on the Mediterranean island of Cyprus. This grave predates early Egyptian art",
"cats spend 2/3 of every day sleeping. That means a nine-year-old cat has",
"for the back.\", \"I like turtles.\", \"I like pie.\", \"Das ist ein rucksack",
"Spanish-Jewish folklore recounts that Adam’s first wife, Lilith, became a black vampire cat,",
"a cat being soft, warm, and fuzzy.\", \"(16) Approximately 40,000 people are bitten",
"face. The tail area and paws also carry the cat’s scent.\", \"(22) Researchers",
"give birth to a litter of between one and nine kittens. The largest",
"= { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\": \"(╯°□°)╯︵",
"\"catfact\": [ \"(1) Unlike dogs, cats do not have a sweet tooth. Scientists",
"Some Siamese cats appear cross-eyed because the nerves from the left side of",
"have magnetized cells in their brains that act as compasses.\", ], } def",
"most popular pets: there are 73 million cats compared to 63 million dogs.",
"that cats have magnetized cells in their brains that act as compasses.\", ],",
"20 inches (50 cm) long and can weigh as little as 2.5 lbs",
"700 pounds (317 kg).\", \"(29) A cat’s brain is biologically more similar to",
"\"(23) When a family cat died in ancient Egypt, family members would mourn",
"embodies the magic and sorcery historically associated with cats.\", \"(46) The smallest wildcat",
"is called “psi-traveling.” Experts think cats either use the angle of the sunlight",
"trigger in messagetext.lower(): replytext = random.choice(multireplydict[trigger]) bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass return \"ok\"",
"patterns in the silk produced in this city.\", \"(38) A cat can jump",
"of trigger words with single 1:1 reply singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\",",
"Egypt, family members would mourn by shaving off their eyebrows. They also held",
"his hand on the cat’s head.\", \"(32) While many parts of Europe and",
"affectionate but also to mark out its territory with scent glands around its",
"in Asia.\", \"(8) There are more than 500 million domestic cats in the",
"with withcraft, and on St. John’s Day, people all over Europe would stuff",
"deep in the throat. To do this, a muscle in the larynx opens",
"long (about the size of a small car) and weigh up to 700",
"produced in this city.\", \"(38) A cat can jump up to five times",
"stored on the ark from being eaten by rats. In reply, God made",
"magic and sorcery historically associated with cats.\", \"(46) The smallest wildcat today is",
"(about the size of a small car) and weigh up to 700 pounds",
"protecting all the food he stored on the ark from being eaten by",
"parts of Europe and North America consider the black cat a sign of",
"became a black vampire cat, sucking the blood from sleeping babies. This may",
"cemetery with tiny mummies of mice.\", \"(24) In 1888, more than 300,000 mummified",
"With the ability to disappear, this mysterious character embodies the magic and sorcery",
"all the food he stored on the ark from being eaten by rats.",
"their brains that are responsible for emotions.\", \"(30) Many Egyptians worshipped the goddess",
"singlereplydict = { \"tableflip\": \"(╯°□°)╯︵ ┻━┻\", \"bagelflip\": \"(╯°□°)╯︵ 🥯\", \"tacoflip\": \"(╯°□°)╯︵ 🌮\", \"pizzaflip\":",
"food. The largest pedigreed cats are Maine Coon cats, which can weigh 25",
"cat a sign of bad luck, in Britain and Australia, black cats are",
"the benevolent fairy godmother figure was a cat.\", \"(49) The little tufts of",
"Iraq. Tabbies got their name because their striped coats resembled the famous wavy",
"(catt, cath, chat, katze) stem from the Latin catus, meaning domestic cat, as",
"That means a nine-year-old cat has been awake for only three years of",
"God made the lion sneeze, and out popped a cat.\", \"(19) A cat’s",
"\"(10) While it is commonly thought that the ancient Egyptians were the first",
"pounds (317 kg).\", \"(29) A cat’s brain is biologically more similar to a",
"meaning domestic cat, as opposed to feles, or wild cat.\", \"(15) The term",
"they drank wine and beat their breasts. The cat was embalmed with a",
"day sleeping. That means a nine-year-old cat has been awake for only three",
"also carry the cat’s scent.\", \"(22) Researchers are unsure exactly how a cat",
"that are responsible for emotions.\", \"(30) Many Egyptians worshipped the goddess Bast, who",
"weigh 25 lbs (11.3 kg), or nearly twice as much as an average",
"“<NAME>”. He cost his owner $50,000, making him one of the most expensive",
"either use the angle of the sunlight to find their way or that",
"\"(18) According to Hebrew legend, Noah prayed to God for help protecting all",
"single bound.\", \"(39) Cats hate the water because their fur does not insulate",
"cats are Maine Coon cats, which can weigh 25 lbs (11.3 kg), or",
"the pack for the back.\", \"I like turtles.\", \"I like pie.\", \"Das ist",
"sleeping baby or suck out the child’s breath.\", \"(45) Perhaps the most famous",
"are more than 500 million domestic cats in the world, with approximately 40",
"burned. Unfortunately, the widespread killing of cats led to an explosion of the",
"way or that cats have magnetized cells in their brains that act as",
"cat’s head.\", \"(31) Mohammed loved cats and reportedly his favorite cat, Muezza, was",
"Many Egyptians worshipped the goddess Bast, who had a woman’s body and a",
"than humans. It is better because cats can see in much dimmer light",
"a “clowder”.\", \"(5) A cat can’t climb head first down a tree because",
"was a French cat named Felicette (a.k.a. “Astrocat”) In 1963, France blasted the",
"sweet tooth. Scientists believe this is due to a mutation in a key",
"Over 30% of households in North America own a cat.\", \"(18) According to",
"grass appears red to cats.\", \"(44) Spanish-Jewish folklore recounts that Adam’s first wife,",
"when it’s wet. The Turkish Van, however, is one cat that likes swimming.",
"┻━┻\", \"musicdance\": \"♪┏(°.°)┛┗(°.°)┓┗(°.°)┛┏(°.°)┓ ♪\", \"shame\": \"🔔 🔔 🔔\", \"shrug\": \"🤷 ¯\\_(ツ)_/¯\", \"disapprove\": \"ಠ_ಠ\",",
"Mediterranean island of Cyprus. This grave predates early Egyptian art depicting cats by",
"a neighborhood in Baghdad, Iraq. Tabbies got their name because their striped coats",
"in singlereplydict: try: if trigger in messagetext.lower(): replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except",
"compared to 63 million dogs. Over 30% of households in North America own",
"much dimmer light and they have a wider peripheral view. It’s worse because",
"cat usually has about 12 whiskers on each side of its face.\", \"(43)",
"tiny mummy was placed in the family tomb or in a pet cemetery",
"\"https://c1.staticflickr.com/3/2254/2334517660_c5a9522dbd.jpg\", \"https://media.giphy.com/media/Xbvni0CPHxdRK/giphy.gif\", \"https://media.giphy.com/media/2oLrxIsfNcMH6/giphy.gif\", ], # source https://www.factretriever.com/cat-facts \"catfact\": [ \"(1) Unlike dogs, cats",
"climb head first down a tree because every claw on a cat’s paw",
"replytext = singlereplydict[trigger] bot.sendMessage(chat_id=chat_id, text=replytext) except AttributeError: pass # these responses have several",
"worse than humans. It is better because cats can see in much dimmer",
"so the cat can land on its feet. Even cats without a tail",
"purrs by vibrating vocal folds deep in the throat. To do this, a",
"cats can see in much dimmer light and they have a wider peripheral",
"the child’s breath.\", \"(45) Perhaps the most famous comic cat is the Cheshire",
"Black Death.\", \"(12) During the Middle Ages, cats were associated with withcraft, and",
"down.\", \"(6) Cats make about 100 different sounds. Dogs make only about 10.\",",
"\"kittyparty\": \"🐈🐱🐆🙌🦁🐅🐯\", \"puppyparty\": \"🐕🐩🐕🙌🐩🐕🐩\", \"ponyparty\": \"🐎🦄🎠🙌🐎🦄🎠\", \"piggyparty\": \"🐖🐽🐷🙌🐷🐽🐖\", \"bunnyparty\": \"🥕🐇🥬🐰🙌🐰🥬🐇🥕\", \"flowerbeam\": \"( ・◡・)つ━☆🌸🌺🌼\",",
"prayed to God for help protecting all the food he stored on the",
"sign of bad luck, in Britain and Australia, black cats are considered lucky.\",",
"people in Athens and other important cities.\", \"(27) The earliest ancestor of the",
"a sign of bad luck, in Britain and Australia, black cats are considered",
"mummy was placed in the family tomb or in a pet cemetery with",
"is probably the oldest breed of cat. In fact, the breed is so",
"was a tabby. Legend says that tabby cats have an “M” for Mohammed",
"a short distance.\", \"(21) A cat rubs against people not only to be",
"reflex.” The eyes and balance organs in the inner ear tell it where",
"40,000 people are bitten by cats in the U.S. annually.\", \"(17) Cats are",
"cats into bonfires. On holy days, people celebrated by tossing cats from church",
"passage about 25 times per second.\", \"(23) When a family cat died in",
"\"(21) A cat rubs against people not only to be affectionate but also",
"or about five large cans of cat food. The largest pedigreed cats are",
"the connotation of a cat being soft, warm, and fuzzy.\", \"(16) Approximately 40,000",
"baby or suck out the child’s breath.\", \"(45) Perhaps the most famous comic"
] |
[
"i): possible = '' for letter in subset: possible += letter if len(possible)",
"itertools # This snippet has been turned into a full repo: # github.com/patrickleweryharris/anagram_solver",
"@rtype: None \"\"\" for i in range(0, len(lst) + 1): for subset in",
"lst: [str] @rtype: None \"\"\" for i in range(0, len(lst) + 1): for",
"in subset: possible += letter if len(possible) == len(lst): # itertools.permutations returns smaller",
"lst @type lst: [str] @rtype: None \"\"\" for i in range(0, len(lst) +",
"\"\"\" for i in range(0, len(lst) + 1): for subset in itertools.permutations(lst, i):",
"@type lst: [str] @rtype: None \"\"\" for i in range(0, len(lst) + 1):",
"been turned into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all",
"possible += letter if len(possible) == len(lst): # itertools.permutations returns smaller lists print(possible)",
"for letter in subset: possible += letter if len(possible) == len(lst): # itertools.permutations",
"for subset in itertools.permutations(lst, i): possible = '' for letter in subset: possible",
"len(possible) == len(lst): # itertools.permutations returns smaller lists print(possible) if __name__ == '__main__':",
"into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations",
"None \"\"\" for i in range(0, len(lst) + 1): for subset in itertools.permutations(lst,",
"for i in range(0, len(lst) + 1): for subset in itertools.permutations(lst, i): possible",
"subset in itertools.permutations(lst, i): possible = '' for letter in subset: possible +=",
"len(lst) + 1): for subset in itertools.permutations(lst, i): possible = '' for letter",
"len(lst): # itertools.permutations returns smaller lists print(possible) if __name__ == '__main__': lst =",
"possible combinations of letters in lst @type lst: [str] @rtype: None \"\"\" for",
"all possible combinations of letters in lst @type lst: [str] @rtype: None \"\"\"",
"# github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations of letters in lst",
"in lst @type lst: [str] @rtype: None \"\"\" for i in range(0, len(lst)",
"a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations of",
"letters in lst @type lst: [str] @rtype: None \"\"\" for i in range(0,",
"lists print(possible) if __name__ == '__main__': lst = ['o', 'r', 'y', 'a', 'n']",
"turned into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible",
"has been turned into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return",
"github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations of letters in lst @type",
"anagram_solver(lst): \"\"\" Return all possible combinations of letters in lst @type lst: [str]",
"possible = '' for letter in subset: possible += letter if len(possible) ==",
"def anagram_solver(lst): \"\"\" Return all possible combinations of letters in lst @type lst:",
"returns smaller lists print(possible) if __name__ == '__main__': lst = ['o', 'r', 'y',",
"print(possible) if __name__ == '__main__': lst = ['o', 'r', 'y', 'a', 'n'] anagram_solver(lst)",
"\"\"\" Return all possible combinations of letters in lst @type lst: [str] @rtype:",
"repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations of letters in",
"if len(possible) == len(lst): # itertools.permutations returns smaller lists print(possible) if __name__ ==",
"full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\" Return all possible combinations of letters",
"smaller lists print(possible) if __name__ == '__main__': lst = ['o', 'r', 'y', 'a',",
"+ 1): for subset in itertools.permutations(lst, i): possible = '' for letter in",
"in itertools.permutations(lst, i): possible = '' for letter in subset: possible += letter",
"subset: possible += letter if len(possible) == len(lst): # itertools.permutations returns smaller lists",
"in range(0, len(lst) + 1): for subset in itertools.permutations(lst, i): possible = ''",
"itertools.permutations(lst, i): possible = '' for letter in subset: possible += letter if",
"== len(lst): # itertools.permutations returns smaller lists print(possible) if __name__ == '__main__': lst",
"# This snippet has been turned into a full repo: # github.com/patrickleweryharris/anagram_solver def",
"of letters in lst @type lst: [str] @rtype: None \"\"\" for i in",
"letter if len(possible) == len(lst): # itertools.permutations returns smaller lists print(possible) if __name__",
"combinations of letters in lst @type lst: [str] @rtype: None \"\"\" for i",
"= '' for letter in subset: possible += letter if len(possible) == len(lst):",
"range(0, len(lst) + 1): for subset in itertools.permutations(lst, i): possible = '' for",
"This snippet has been turned into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst):",
"i in range(0, len(lst) + 1): for subset in itertools.permutations(lst, i): possible =",
"1): for subset in itertools.permutations(lst, i): possible = '' for letter in subset:",
"itertools.permutations returns smaller lists print(possible) if __name__ == '__main__': lst = ['o', 'r',",
"letter in subset: possible += letter if len(possible) == len(lst): # itertools.permutations returns",
"import itertools # This snippet has been turned into a full repo: #",
"'' for letter in subset: possible += letter if len(possible) == len(lst): #",
"Return all possible combinations of letters in lst @type lst: [str] @rtype: None",
"[str] @rtype: None \"\"\" for i in range(0, len(lst) + 1): for subset",
"snippet has been turned into a full repo: # github.com/patrickleweryharris/anagram_solver def anagram_solver(lst): \"\"\"",
"# itertools.permutations returns smaller lists print(possible) if __name__ == '__main__': lst = ['o',",
"+= letter if len(possible) == len(lst): # itertools.permutations returns smaller lists print(possible) if"
] |
[
"def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed():",
"@staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def",
"= 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0",
"joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes =",
"0 for i in range(15)] joy_msg.axes[2] = 1.0 joy_msg.axes[5] = 1.0 return joy_msg",
"def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed():",
"from sensor_msgs.msg import Joy class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5]",
"return joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0 for",
"joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg =",
"def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller():",
"<filename>pwm_motor_control_ros/test/integration/pwm_test_support/xbox_controller_joy_stub.py from sensor_msgs.msg import Joy class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller()",
"for i in range(8)] joy_msg.buttons = [ 0 for i in range(15)] joy_msg.axes[2]",
"-1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return",
"joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg =",
"joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod",
"joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] =",
"@staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0 for i in",
"sensor_msgs.msg import Joy class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] =",
"@staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def",
"def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed():",
"return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg",
"@staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def",
"= XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg = Joy()",
"= XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller()",
"return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg",
"XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2]",
"range(8)] joy_msg.buttons = [ 0 for i in range(15)] joy_msg.axes[2] = 1.0 joy_msg.axes[5]",
"joy_msg.buttons = [ 0 for i in range(15)] joy_msg.axes[2] = 1.0 joy_msg.axes[5] =",
"joy_msg.axes = [ 0.0 for i in range(8)] joy_msg.buttons = [ 0 for",
"0.0 return joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0",
"i in range(8)] joy_msg.buttons = [ 0 for i in range(15)] joy_msg.axes[2] =",
"= 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes = [",
"= XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller()",
"= XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller()",
"Joy class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return",
"joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod",
"-1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return",
"joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod",
"def idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0 for i in range(8)]",
"= [ 0.0 for i in range(8)] joy_msg.buttons = [ 0 for i",
"= -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0",
"XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2]",
"right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg",
"in range(8)] joy_msg.buttons = [ 0 for i in range(15)] joy_msg.axes[2] = 1.0",
"joy_msg = Joy() joy_msg.axes = [ 0.0 for i in range(8)] joy_msg.buttons =",
"XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes",
"XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5]",
"@staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def",
"joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] =",
"left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg",
"class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg",
"XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0 return joy_msg @staticmethod",
"joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return joy_msg @staticmethod def left_trigger_half_depressed(): joy_msg =",
"return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg",
"Joy() joy_msg.axes = [ 0.0 for i in range(8)] joy_msg.buttons = [ 0",
"joy_msg.axes[5] = -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] =",
"left_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg",
"= -1.0 return joy_msg @staticmethod def right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0",
"right_trigger_half_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = 0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg",
"idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0 for i in range(8)] joy_msg.buttons",
"joy_msg @staticmethod def idle_controller(): joy_msg = Joy() joy_msg.axes = [ 0.0 for i",
"= Joy() joy_msg.axes = [ 0.0 for i in range(8)] joy_msg.buttons = [",
"[ 0.0 for i in range(8)] joy_msg.buttons = [ 0 for i in",
"= [ 0 for i in range(15)] joy_msg.axes[2] = 1.0 joy_msg.axes[5] = 1.0",
"joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = 0.0 return joy_msg @staticmethod def idle_controller(): joy_msg =",
"[ 0 for i in range(15)] joy_msg.axes[2] = 1.0 joy_msg.axes[5] = 1.0 return",
"0.0 return joy_msg @staticmethod def left_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[2] = -1.0 return",
"0.0 for i in range(8)] joy_msg.buttons = [ 0 for i in range(15)]",
"import Joy class XboxControllerJoyStub: @staticmethod def right_trigger_depressed(): joy_msg = XboxControllerJoyStub.idle_controller() joy_msg.axes[5] = -1.0"
] |
[
"Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer):",
"head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name):",
"__init__(self, repository): self.logger = Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name =",
"HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4]",
"self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head and master:\")",
"= ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name, branch_name) return",
"def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head and master:\") self.log_from_head_to_merge_base =",
"import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger =",
"master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch",
"commit ids between the current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head",
"walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex",
"args = ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def",
"head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit",
"[] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\")",
"generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head and master:\") self.log_from_head_to_merge_base = []",
"head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name,",
"RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger",
"self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker",
"self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head and master:\") self.log_from_head_to_merge_base",
"self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def",
"walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for",
"self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^",
"repository): self.logger = Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:]",
"= BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def",
"executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name, branch_name)",
"= self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head and",
"self.logger.log(\"Determining commit ids between the current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v",
"= Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def",
"self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker =",
"self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between",
"head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self):",
"branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return",
"other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output()",
"BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self,",
"args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name, branch_name) return merge_base in",
"and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id)",
"self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base)",
"head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base():",
"current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id in",
"from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository",
"branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base =",
"ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name, branch_name) return merge_base",
"= self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args",
"self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining",
"commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base',",
"import BranchFilterer from Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import",
"BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self)",
"class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository = repository self.repository_directory =",
"['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name):",
"^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch =",
"= self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in",
"master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id)",
"between the current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for",
"Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository = repository self.repository_directory",
"self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch):",
"ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self,",
"def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name]",
"repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids",
"self.head_branch_name) walker = BranchToCommitWalker(self.repository, head_master_merge_base) head_branch = self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield",
"Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self):",
"self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current head",
"return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name, branch_name) return merge_base in self.log_from_head_to_merge_base",
"for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git',",
"= [] self.logger.log(\"v head v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master",
"def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory,",
"in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name,",
"self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name) walker = BranchToCommitWalker(self.repository,",
"from BranchFilters.BranchFilterer import BranchFilterer from Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from",
"BranchFilterer from Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger",
"'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base",
"import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def",
"self.repository.branches[self.head_branch_name] for commit in walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args =",
"for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base =",
"the current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\") for id",
"get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args)",
"other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self, branch_name): merge_base = self.get_merge_base(self.head_branch_name,",
"in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\", self.head_branch_name)",
"BranchFilters.BranchFilterer import BranchFilterer from Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger",
"self.logger = Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base()",
"from Interoperability.ShellCommandExecuter import ShellCommandExecuter from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class",
"= repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the",
"id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base = self.get_merge_base(\"master\",",
"walker.walk(head_branch): yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name]",
"repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit ids between the current",
"commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer =",
"= ['git', 'merge-base', branch_name, other_branch_name] executer = ShellCommandExecuter(self.repository_directory, args) return executer.execute_for_output() def should_include_branch(self,",
"v\") for id in self.walk_log_from_head_to_merge_base(): self.log_from_head_to_merge_base.append(id) self.logger.log(id) self.logger.log(\"^ master ^\") def walk_log_from_head_to_merge_base(self): head_master_merge_base",
"ids between the current head and master:\") self.log_from_head_to_merge_base = [] self.logger.log(\"v head v\")",
"yield commit.hex def get_merge_base(self, branch_name, other_branch_name): args = ['git', 'merge-base', branch_name, other_branch_name] executer",
"import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository = repository",
"Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository): self.logger = Logger(self) self.repository =",
"= repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name = self.repository.head.name[11:] self.generate_log_from_head_to_merge_base() def generate_log_from_head_to_merge_base(self): self.logger.log(\"Determining commit",
"def __init__(self, repository): self.logger = Logger(self) self.repository = repository self.repository_directory = repr(repository).split('\\'')[1][:-4] self.head_branch_name",
"from RepositoryWalkers.BranchToCommitWalker import BranchToCommitWalker from Logger import Logger class HeadToMasterBranchFilterer(BranchFilterer): def __init__(self, repository):"
] |
[] |
[
"from bokeh.models import CategoricalColorMapper # Convert df to a ColumnDataSource: source source =",
"ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red',",
"where the automobile was manufactured. The origin column will be used in the",
"using the CategoricalColorMapper to color each glyph by a categorical property. Here, you're",
"the CategoricalColorMapper() function. It has two parameters here: factors and palette. Add a",
"as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df to",
"as a Pandas DataFrame called df. The figure is provided for you as",
"column will be used in the ColorMapper to color automobiles manufactured in the",
"transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper # Convert df",
"in the ColorMapper to color automobiles manufactured in the US as blue, Europe",
"plot miles-per-gallon vs weight and color each circle glyph by the region where",
"used in the ColorMapper to color automobiles manufactured in the US as blue,",
"two parameters here: factors and palette. Add a circle glyph to the figure",
"origin column will be used in the ColorMapper to color automobiles manufactured in",
"manufactured. The origin column will be used in the ColorMapper to color automobiles",
"It has two parameters here: factors and palette. Add a circle glyph to",
"to plot 'mpg' (on the y-axis) vs 'weight' (on the x-axis). Remember to",
"glyph by a categorical property. Here, you're going to use the automobile dataset",
"done for you. Make a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function.",
"a ColumnDataSource: source source = ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper",
"you're going to use the automobile dataset to plot miles-per-gallon vs weight and",
"to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the",
"was manufactured. The origin column will be used in the ColorMapper to color",
"as green. The automobile data set is provided to you as a Pandas",
"to color automobiles manufactured in the US as blue, Europe as red and",
"transform=color_mapper), legend='origin') # Specify the name of the output file and show the",
"object called color_mapper with the CategoricalColorMapper() function. It has two parameters here: factors",
"glyph to the figure p to plot 'mpg' (on the y-axis) vs 'weight'",
"plot 'mpg' (on the y-axis) vs 'weight' (on the x-axis). Remember to pass",
"Europe as red and Asia as green. The automobile data set is provided",
"called df. The figure is provided for you as p. INSTRUCTIONS 100XP Import",
"is provided to you as a Pandas DataFrame called df. The figure is",
"you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df",
"bokeh.models from bokeh.models import CategoricalColorMapper # Convert df to a ColumnDataSource: source source",
"Specify the name of the output file and show the result output_file('colormap.html') show(p)",
"''' Colormapping The final glyph customization we'll practice is using the CategoricalColorMapper to",
"function. It has two parameters here: factors and palette. Add a circle glyph",
"pass in source and 'origin' as arguments to source and legend. For the",
"source. This has already been done for you. Make a CategoricalColorMapper object called",
"color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a circle",
"Asia as green. The automobile data set is provided to you as a",
"# Convert df to a ColumnDataSource: source source = ColumnDataSource(df) # Make a",
"to use the automobile dataset to plot miles-per-gallon vs weight and color each",
"'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a circle glyph to the figure",
"the ColorMapper to color automobiles manufactured in the US as blue, Europe as",
"is provided for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert",
"by the region where the automobile was manufactured. The origin column will be",
"ColumnDataSource called source. This has already been done for you. Make a CategoricalColorMapper",
"to a ColumnDataSource: source source = ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper",
"glyph by the region where the automobile was manufactured. The origin column will",
"parameters here: factors and palette. Add a circle glyph to the figure p",
"to pass in source and 'origin' as arguments to source and legend. For",
"= CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a circle glyph to",
"been done for you. Make a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper()",
"'origin' as arguments to source and legend. For the color parameter, use dict(field='origin',",
"by a categorical property. Here, you're going to use the automobile dataset to",
"and palette. Add a circle glyph to the figure p to plot 'mpg'",
"Pandas DataFrame called df. The figure is provided for you as p. INSTRUCTIONS",
"INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df to a ColumnDataSource",
"use the automobile dataset to plot miles-per-gallon vs weight and color each circle",
"glyph customization we'll practice is using the CategoricalColorMapper to color each glyph by",
"the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models",
"practice is using the CategoricalColorMapper to color each glyph by a categorical property.",
"'US'], palette=['red', 'green', 'blue']) # Add a circle glyph to the figure p",
"parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper",
"called source. This has already been done for you. Make a CategoricalColorMapper object",
"p to plot 'mpg' (on the y-axis) vs 'weight' (on the x-axis). Remember",
"a circle glyph to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin')",
"and color each circle glyph by the region where the automobile was manufactured.",
"Convert the DataFrame df to a ColumnDataSource called source. This has already been",
"each circle glyph by the region where the automobile was manufactured. The origin",
"color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of the output file and show",
"circle glyph to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') #",
"manufactured in the US as blue, Europe as red and Asia as green.",
"called color_mapper with the CategoricalColorMapper() function. It has two parameters here: factors and",
"figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of",
"a categorical property. Here, you're going to use the automobile dataset to plot",
"df to a ColumnDataSource: source source = ColumnDataSource(df) # Make a CategoricalColorMapper object:",
"in source and 'origin' as arguments to source and legend. For the color",
"figure p to plot 'mpg' (on the y-axis) vs 'weight' (on the x-axis).",
"CategoricalColorMapper to color each glyph by a categorical property. Here, you're going to",
"'blue']) # Add a circle glyph to the figure p p.circle('weight', 'mpg', source=source,",
"legend='origin') # Specify the name of the output file and show the result",
"# Add a circle glyph to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin',",
"will be used in the ColorMapper to color automobiles manufactured in the US",
"each glyph by a categorical property. Here, you're going to use the automobile",
"CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add",
"automobiles manufactured in the US as blue, Europe as red and Asia as",
"Here, you're going to use the automobile dataset to plot miles-per-gallon vs weight",
"a ColumnDataSource called source. This has already been done for you. Make a",
"with the CategoricalColorMapper() function. It has two parameters here: factors and palette. Add",
"blue, Europe as red and Asia as green. The automobile data set is",
"The automobile data set is provided to you as a Pandas DataFrame called",
"provided for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the",
"vs 'weight' (on the x-axis). Remember to pass in source and 'origin' as",
"source and 'origin' as arguments to source and legend. For the color parameter,",
"Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df to a ColumnDataSource called source.",
"Colormapping The final glyph customization we'll practice is using the CategoricalColorMapper to color",
"The final glyph customization we'll practice is using the CategoricalColorMapper to color each",
"DataFrame df to a ColumnDataSource called source. This has already been done for",
"'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of the output file",
"bokeh.models. Convert the DataFrame df to a ColumnDataSource called source. This has already",
"the automobile was manufactured. The origin column will be used in the ColorMapper",
"has two parameters here: factors and palette. Add a circle glyph to the",
"region where the automobile was manufactured. The origin column will be used in",
"p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df to a",
"object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a",
"US as blue, Europe as red and Asia as green. The automobile data",
"going to use the automobile dataset to plot miles-per-gallon vs weight and color",
"This has already been done for you. Make a CategoricalColorMapper object called color_mapper",
"the x-axis). Remember to pass in source and 'origin' as arguments to source",
"for you. Make a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function. It",
"green. The automobile data set is provided to you as a Pandas DataFrame",
"to you as a Pandas DataFrame called df. The figure is provided for",
"circle glyph to the figure p to plot 'mpg' (on the y-axis) vs",
"set is provided to you as a Pandas DataFrame called df. The figure",
"you as a Pandas DataFrame called df. The figure is provided for you",
"color_mapper with the CategoricalColorMapper() function. It has two parameters here: factors and palette.",
"'mpg' (on the y-axis) vs 'weight' (on the x-axis). Remember to pass in",
"the y-axis) vs 'weight' (on the x-axis). Remember to pass in source and",
"color automobiles manufactured in the US as blue, Europe as red and Asia",
"factors and palette. Add a circle glyph to the figure p to plot",
"categorical property. Here, you're going to use the automobile dataset to plot miles-per-gallon",
"to the figure p to plot 'mpg' (on the y-axis) vs 'weight' (on",
"automobile data set is provided to you as a Pandas DataFrame called df.",
"y-axis) vs 'weight' (on the x-axis). Remember to pass in source and 'origin'",
"color each glyph by a categorical property. Here, you're going to use the",
"dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper # Convert",
"DataFrame called df. The figure is provided for you as p. INSTRUCTIONS 100XP",
"as red and Asia as green. The automobile data set is provided to",
"source = ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia',",
"df. The figure is provided for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper",
"weight and color each circle glyph by the region where the automobile was",
"#Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper # Convert df to a",
"to source and legend. For the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import",
"final glyph customization we'll practice is using the CategoricalColorMapper to color each glyph",
"data set is provided to you as a Pandas DataFrame called df. The",
"in the US as blue, Europe as red and Asia as green. The",
"color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a circle glyph",
"(on the x-axis). Remember to pass in source and 'origin' as arguments to",
"customization we'll practice is using the CategoricalColorMapper to color each glyph by a",
"and 'origin' as arguments to source and legend. For the color parameter, use",
"import CategoricalColorMapper # Convert df to a ColumnDataSource: source source = ColumnDataSource(df) #",
"and Asia as green. The automobile data set is provided to you as",
"'green', 'blue']) # Add a circle glyph to the figure p p.circle('weight', 'mpg',",
"glyph to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify",
"be used in the ColorMapper to color automobiles manufactured in the US as",
"CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function. It has two parameters here:",
"df to a ColumnDataSource called source. This has already been done for you.",
"use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper #",
"automobile was manufactured. The origin column will be used in the ColorMapper to",
"Remember to pass in source and 'origin' as arguments to source and legend.",
"= ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'],",
"the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name",
"legend. For the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models",
"automobile dataset to plot miles-per-gallon vs weight and color each circle glyph by",
"red and Asia as green. The automobile data set is provided to you",
"''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper # Convert df to",
"already been done for you. Make a CategoricalColorMapper object called color_mapper with the",
"a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function. It has two parameters",
"has already been done for you. Make a CategoricalColorMapper object called color_mapper with",
"figure is provided for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models.",
"vs weight and color each circle glyph by the region where the automobile",
"a circle glyph to the figure p to plot 'mpg' (on the y-axis)",
"here: factors and palette. Add a circle glyph to the figure p to",
"CategoricalColorMapper from bokeh.models. Convert the DataFrame df to a ColumnDataSource called source. This",
"p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of the",
"color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from bokeh.models import",
"'weight' (on the x-axis). Remember to pass in source and 'origin' as arguments",
"CategoricalColorMapper from bokeh.models from bokeh.models import CategoricalColorMapper # Convert df to a ColumnDataSource:",
"The origin column will be used in the ColorMapper to color automobiles manufactured",
"from bokeh.models from bokeh.models import CategoricalColorMapper # Convert df to a ColumnDataSource: source",
"the automobile dataset to plot miles-per-gallon vs weight and color each circle glyph",
"and legend. For the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from",
"the figure p to plot 'mpg' (on the y-axis) vs 'weight' (on the",
"# Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green',",
"dataset to plot miles-per-gallon vs weight and color each circle glyph by the",
"palette. Add a circle glyph to the figure p to plot 'mpg' (on",
"property. Here, you're going to use the automobile dataset to plot miles-per-gallon vs",
"to plot miles-per-gallon vs weight and color each circle glyph by the region",
"x-axis). Remember to pass in source and 'origin' as arguments to source and",
"as blue, Europe as red and Asia as green. The automobile data set",
"100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame df to a ColumnDataSource called",
"as arguments to source and legend. For the color parameter, use dict(field='origin', transform=color_mapper).",
"the DataFrame df to a ColumnDataSource called source. This has already been done",
"for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from bokeh.models. Convert the DataFrame",
"is using the CategoricalColorMapper to color each glyph by a categorical property. Here,",
"the US as blue, Europe as red and Asia as green. The automobile",
"from bokeh.models. Convert the DataFrame df to a ColumnDataSource called source. This has",
"Add a circle glyph to the figure p to plot 'mpg' (on the",
"Add a circle glyph to the figure p p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper),",
"bokeh.models import CategoricalColorMapper # Convert df to a ColumnDataSource: source source = ColumnDataSource(df)",
"circle glyph by the region where the automobile was manufactured. The origin column",
"the region where the automobile was manufactured. The origin column will be used",
"the CategoricalColorMapper to color each glyph by a categorical property. Here, you're going",
"For the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper from bokeh.models from",
"Convert df to a ColumnDataSource: source source = ColumnDataSource(df) # Make a CategoricalColorMapper",
"CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) # Add a circle glyph to the",
"a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue']) #",
"arguments to source and legend. For the color parameter, use dict(field='origin', transform=color_mapper). '''",
"Make a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function. It has two",
"palette=['red', 'green', 'blue']) # Add a circle glyph to the figure p p.circle('weight',",
"to a ColumnDataSource called source. This has already been done for you. Make",
"p.circle('weight', 'mpg', source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of the output",
"to color each glyph by a categorical property. Here, you're going to use",
"provided to you as a Pandas DataFrame called df. The figure is provided",
"The figure is provided for you as p. INSTRUCTIONS 100XP Import CategoricalColorMapper from",
"(on the y-axis) vs 'weight' (on the x-axis). Remember to pass in source",
"source and legend. For the color parameter, use dict(field='origin', transform=color_mapper). ''' #Import CategoricalColorMapper",
"color each circle glyph by the region where the automobile was manufactured. The",
"source=source, color=dict(field='origin', transform=color_mapper), legend='origin') # Specify the name of the output file and",
"ColumnDataSource: source source = ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper =",
"Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe', 'Asia', 'US'], palette=['red', 'green', 'blue'])",
"ColorMapper to color automobiles manufactured in the US as blue, Europe as red",
"a Pandas DataFrame called df. The figure is provided for you as p.",
"source source = ColumnDataSource(df) # Make a CategoricalColorMapper object: color_mapper color_mapper = CategoricalColorMapper(factors=['Europe',",
"miles-per-gallon vs weight and color each circle glyph by the region where the",
"you. Make a CategoricalColorMapper object called color_mapper with the CategoricalColorMapper() function. It has",
"we'll practice is using the CategoricalColorMapper to color each glyph by a categorical",
"CategoricalColorMapper() function. It has two parameters here: factors and palette. Add a circle",
"CategoricalColorMapper # Convert df to a ColumnDataSource: source source = ColumnDataSource(df) # Make",
"# Specify the name of the output file and show the result output_file('colormap.html')"
] |
[
"is None: continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle",
"ESI returns a retryable error, 0 disables, -1 is unlimited loop -- Event",
"def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url -- Url to",
"ESI retries -- Number of retries when ESI returns a retryable error, 0",
"a path for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is",
"= \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {})",
"EsiCache\") session = self.args.get('session') if session is not None: if not isinstance(type(session), aiohttp.ClientSession):",
"url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths =",
"retries when ESI returns a retryable error, 0 disables, -1 is unlimited loop",
"of retries when ESI returns a retryable error, 0 disables, -1 is unlimited",
"\"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {}) #each",
"**kwargs): \"\"\" Initialize the class Arguments: swagger_url -- Url to the swagger spec",
"raise TypeError(\"session must be a aiohttp ClientSession\") self.operations = {} self.data = {}",
"path for route, verbs in paths.items(): #each http verb in a path for",
"swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url -- Url to the swagger",
"loop -- Event loop to use for asyncio session -- aiohttp session to",
"to ESI retries -- Number of retries when ESI returns a retryable error,",
"def __analyze_swagger(self): #Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\")",
"loop to use for asyncio session -- aiohttp session to use, note: loop",
"EsiCache, DictCache from .esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object):",
"base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths",
"error, 0 disables, -1 is unlimited loop -- Event loop to use for",
"#each http verb in a path for verb, operation in verbs.items(): operation_id =",
"= operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter refs params =",
"set with session, set the loop you want in the session instead \"\"\"",
"issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the type EsiCache\") session = self.args.get('session')",
"= self.data.get(\"paths\", {}) #each path for route, verbs in paths.items(): #each http verb",
"retries -- Number of retries when ESI returns a retryable error, 0 disables,",
"esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url,",
"continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter refs",
"__analyze_swagger(self): #Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat",
"param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split",
"is not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp",
"= {} self.data = {} r = requests.get(swagger_url) try: data = r.json() except:",
"user_agent -- user agent to send with ESI calls cache -- EsiCache object",
"EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get base url self.base_url = \"https://\"",
"self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {}) #each path for route, verbs",
"else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op",
"new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split = path.split(\"/\") if",
"import json from .op import EsiOp from .auth import EsiAuth from .cache import",
"the class Arguments: swagger_url -- Url to the swagger spec Keyword arguments: user_agent",
"class creates \"EsiOp\" operations based on a provided swagger spec \"\"\" def __init__(self,",
"of the type EsiCache\") session = self.args.get('session') if session is not None: if",
"kwargs.get(\"cache\", DictCache()) if cache is not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache",
"{} self.data = {} r = requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse",
"to send with ESI calls cache -- EsiCache object to use for caching",
"in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None: continue new_op = operation.copy()",
"operation_id = operation.get(\"operationId\") if operation_id is None: continue new_op = operation.copy() new_op[\"path\"] =",
"new_op[\"verb\"] = verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for",
"not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the type",
"be useless if set with session, set the loop you want in the",
"swagger_url -- Url to the swagger spec Keyword arguments: user_agent -- user agent",
"agent to send with ESI calls cache -- EsiCache object to use for",
"for param in params: path = param.get(\"$ref\") if path is None: param_details =",
"cache is not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of",
"session instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is",
".auth import EsiAuth from .cache import EsiCache, DictCache from .esisession import EsiSession import",
"not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\") self.operations = {}",
"self.data.get(\"paths\", {}) #each path for route, verbs in paths.items(): #each http verb in",
"r.close() self.data = data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return",
"if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the type EsiCache\") session",
"0 disables, -1 is unlimited loop -- Event loop to use for asyncio",
"= operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params: path = param.get(\"$ref\") if",
"json from .op import EsiOp from .auth import EsiAuth from .cache import EsiCache,",
"-- Number of retries when ESI returns a retryable error, 0 disables, -1",
"\"EsiOp\" operations based on a provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs):",
"TypeError(\"session must be a aiohttp ClientSession\") self.operations = {} self.data = {} r",
"is None: param_details = param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name]",
"\"\"\" The EsiPysi class creates \"EsiOp\" operations based on a provided swagger spec",
"def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get base",
"self.operations[operation_id] = new_op def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0] != \"#\":",
"session def __analyze_swagger(self): #Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\",",
"in the session instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if",
"http verb in a path for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\")",
"refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params: path =",
"cache = kwargs.get(\"cache\", DictCache()) if cache is not None: if not issubclass(type(cache), EsiCache):",
"spec Keyword arguments: user_agent -- user agent to send with ESI calls cache",
"if set with session, set the loop you want in the session instead",
"session -- aiohttp session to use, note: loop will be useless if set",
"param in params: path = param.get(\"$ref\") if path is None: param_details = param.copy()",
"= param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0]",
"verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None: continue new_op",
"Keyword arguments: user_agent -- user agent to send with ESI calls cache --",
"creates \"EsiOp\" operations based on a provided swagger spec \"\"\" def __init__(self, swagger_url,",
"finally: r.close() self.data = data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args)",
"swagger spec Keyword arguments: user_agent -- user agent to send with ESI calls",
"error, spec written to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally:",
"The EsiPysi class creates \"EsiOp\" operations based on a provided swagger spec \"\"\"",
"= {} r = requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error, spec",
"ClientSession\") self.operations = {} self.data = {} r = requests.get(swagger_url) try: data =",
"self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {}) #each path for",
"= data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session def",
"from .esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The",
"data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self):",
"paths = self.data.get(\"paths\", {}) #each path for route, verbs in paths.items(): #each http",
"#Reformat json paths = self.data.get(\"paths\", {}) #each path for route, verbs in paths.items():",
"should be of the type EsiCache\") session = self.args.get('session') if session is not",
"session = self.args.get('session') if session is not None: if not isinstance(type(session), aiohttp.ClientSession): raise",
"self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self, path):",
"not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\")",
"unlimited loop -- Event loop to use for asyncio session -- aiohttp session",
"EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations based on a provided swagger",
"-- EsiAuth to use for authorized calls to ESI retries -- Number of",
"logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return",
"in a path for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id",
"swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url",
"r.json() except: logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json', 'w') as esifile:",
"calls cache -- EsiCache object to use for caching auth -- EsiAuth to",
"parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params: path",
"new_op[\"parameters\"] = {} for param in params: path = param.get(\"$ref\") if path is",
"Event loop to use for asyncio session -- aiohttp session to use, note:",
"!= \"#\": #Unsupported return None ref = self.data for i in range(1, len(path_split)):",
"in params: path = param.get(\"$ref\") if path is None: param_details = param.copy() else:",
"loop you want in the session instead \"\"\" self.args = kwargs cache =",
"provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments:",
"operation_id is None: continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb",
"r = requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error, spec written to",
"verb in a path for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if",
"\"\") #Reformat json paths = self.data.get(\"paths\", {}) #each path for route, verbs in",
"verbs in paths.items(): #each http verb in a path for verb, operation in",
"file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close() self.data = data",
"= self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self,",
"-- user agent to send with ESI calls cache -- EsiCache object to",
"to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close() self.data =",
"in paths.items(): #each http verb in a path for verb, operation in verbs.items():",
"self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\",",
"new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter refs params",
"import asyncio import aiohttp import requests import json from .op import EsiOp from",
"EsiAuth from .cache import EsiCache, DictCache from .esisession import EsiSession import logging logger",
"new_op def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported return",
"EsiCache): raise TypeError(\"cache should be of the type EsiCache\") session = self.args.get('session') if",
"= {} for param in params: path = param.get(\"$ref\") if path is None:",
"requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error, spec written to file\") with",
"= kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is not None: if not",
"logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations based",
"operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter refs params = operation.get(\"parameters\")",
"disables, -1 is unlimited loop -- Event loop to use for asyncio session",
"self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get",
"use for asyncio session -- aiohttp session to use, note: loop will be",
"if path_split[0] != \"#\": #Unsupported return None ref = self.data for i in",
"-- EsiCache object to use for caching auth -- EsiAuth to use for",
"verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in",
"user agent to send with ESI calls cache -- EsiCache object to use",
"= self.data for i in range(1, len(path_split)): ref = ref.get(path_split[i], {}) return ref",
"+ self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {}) #each path for route,",
"authorized calls to ESI retries -- Number of retries when ESI returns a",
"Url to the swagger spec Keyword arguments: user_agent -- user agent to send",
"None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the type EsiCache\")",
"based on a provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize",
"be a aiohttp ClientSession\") self.operations = {} self.data = {} r = requests.get(swagger_url)",
"{} r = requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error, spec written",
"asyncio session -- aiohttp session to use, note: loop will be useless if",
"with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger()",
"EsiPysi class creates \"EsiOp\" operations based on a provided swagger spec \"\"\" def",
"type EsiCache\") session = self.args.get('session') if session is not None: if not isinstance(type(session),",
"params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params: path = param.get(\"$ref\")",
"loop will be useless if set with session, set the loop you want",
"a provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class",
".esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi",
"= param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id]",
"return finally: r.close() self.data = data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations,",
"param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0] !=",
"None: continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter",
"retryable error, 0 disables, -1 is unlimited loop -- Event loop to use",
"DictCache()) if cache is not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should",
"operation.get(\"operationId\") if operation_id is None: continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"]",
"if path is None: param_details = param.copy() else: param_details = self.__get_ref(path) param_name =",
"self.data = data self.__analyze_swagger() def session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session",
"paths.items(): #each http verb in a path for verb, operation in verbs.items(): operation_id",
"**self.args) return session def __analyze_swagger(self): #Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\")",
"is unlimited loop -- Event loop to use for asyncio session -- aiohttp",
"with ESI calls cache -- EsiCache object to use for caching auth --",
"\"\"\" Initialize the class Arguments: swagger_url -- Url to the swagger spec Keyword",
"as esifile: esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger() def session(self): session",
"\"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url -- Url",
"None ref = self.data for i in range(1, len(path_split)): ref = ref.get(path_split[i], {})",
"for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None: continue",
"operations based on a provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\"",
"-- aiohttp session to use, note: loop will be useless if set with",
"be of the type EsiCache\") session = self.args.get('session') if session is not None:",
"session is not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a",
"written to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close() self.data",
"to use for asyncio session -- aiohttp session to use, note: loop will",
"the loop you want in the session instead \"\"\" self.args = kwargs cache",
"-1 is unlimited loop -- Event loop to use for asyncio session --",
"param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] =",
"Number of retries when ESI returns a retryable error, 0 disables, -1 is",
"__init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url -- Url to the",
"EsiOp from .auth import EsiAuth from .cache import EsiCache, DictCache from .esisession import",
"if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\") self.operations =",
"\"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is not None:",
"you want in the session instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\",",
"#Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params:",
"use, note: loop will be useless if set with session, set the loop",
"path_split[0] != \"#\": #Unsupported return None ref = self.data for i in range(1,",
"self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is not None: if",
"import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\"",
"auth -- EsiAuth to use for authorized calls to ESI retries -- Number",
"with session, set the loop you want in the session instead \"\"\" self.args",
"kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is not None: if not issubclass(type(cache),",
"from .op import EsiOp from .auth import EsiAuth from .cache import EsiCache, DictCache",
"= requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error, spec written to file\")",
"import EsiCache, DictCache from .esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class",
"from .auth import EsiAuth from .cache import EsiCache, DictCache from .esisession import EsiSession",
"{}) #each path for route, verbs in paths.items(): #each http verb in a",
"send with ESI calls cache -- EsiCache object to use for caching auth",
"isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\") self.operations = {} self.data",
"= verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {} for param",
"route new_op[\"verb\"] = verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] = {}",
"return session def __analyze_swagger(self): #Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") +",
"requests import json from .op import EsiOp from .auth import EsiAuth from .cache",
"EsiCache object to use for caching auth -- EsiAuth to use for authorized",
"the type EsiCache\") session = self.args.get('session') if session is not None: if not",
"import EsiOp from .auth import EsiAuth from .cache import EsiCache, DictCache from .esisession",
"= route new_op[\"verb\"] = verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"] =",
"aiohttp session to use, note: loop will be useless if set with session,",
"import aiohttp import requests import json from .op import EsiOp from .auth import",
"= path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None ref = self.data for",
"Arguments: swagger_url -- Url to the swagger spec Keyword arguments: user_agent -- user",
"def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None",
"for asyncio session -- aiohttp session to use, note: loop will be useless",
"if cache is not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be",
"self.args.get('session') if session is not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must",
"is not None: if not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the",
"aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\") self.operations = {} self.data =",
"will be useless if set with session, set the loop you want in",
"return None ref = self.data for i in range(1, len(path_split)): ref = ref.get(path_split[i],",
"spec written to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close()",
"= self.args.get('session') if session is not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session",
"import requests import json from .op import EsiOp from .auth import EsiAuth from",
"want in the session instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache())",
"param_details = param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details",
"__get_ref(self, path): path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None ref",
"EsiAuth to use for authorized calls to ESI retries -- Number of retries",
"to use, note: loop will be useless if set with session, set the",
"to the swagger spec Keyword arguments: user_agent -- user agent to send with",
"class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations based on a provided",
"= operation.get(\"operationId\") if operation_id is None: continue new_op = operation.copy() new_op[\"path\"] = route",
"ref = self.data for i in range(1, len(path_split)): ref = ref.get(path_split[i], {}) return",
"= new_op def __get_ref(self, path): path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported",
".op import EsiOp from .auth import EsiAuth from .cache import EsiCache, DictCache from",
"calls to ESI retries -- Number of retries when ESI returns a retryable",
"path is None: param_details = param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\")",
"class Arguments: swagger_url -- Url to the swagger spec Keyword arguments: user_agent --",
"param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def",
"path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None ref = self.data",
"None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be a aiohttp ClientSession\") self.operations",
"if session is not None: if not isinstance(type(session), aiohttp.ClientSession): raise TypeError(\"session must be",
"open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger() def",
"esifile: esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger() def session(self): session =",
"try: data = r.json() except: logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json',",
"new_op[\"path\"] = route new_op[\"verb\"] = verb #Handle parameter refs params = operation.get(\"parameters\") new_op[\"parameters\"]",
"-- Event loop to use for asyncio session -- aiohttp session to use,",
"param.get(\"$ref\") if path is None: param_details = param.copy() else: param_details = self.__get_ref(path) param_name",
"cache -- EsiCache object to use for caching auth -- EsiAuth to use",
".cache import EsiCache, DictCache from .esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\")",
"to use for caching auth -- EsiAuth to use for authorized calls to",
"path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None ref = self.data for i",
"+ self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json paths = self.data.get(\"paths\", {}) #each path",
"session to use, note: loop will be useless if set with session, set",
"= r.json() except: logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json', 'w') as",
"= logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations based on",
"asyncio import aiohttp import requests import json from .op import EsiOp from .auth",
"param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split = path.split(\"/\")",
"a aiohttp ClientSession\") self.operations = {} self.data = {} r = requests.get(swagger_url) try:",
"ESI calls cache -- EsiCache object to use for caching auth -- EsiAuth",
"params: path = param.get(\"$ref\") if path is None: param_details = param.copy() else: param_details",
"logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations",
"self.operations, **self.args) return session def __analyze_swagger(self): #Get base url self.base_url = \"https://\" +",
"raise TypeError(\"cache should be of the type EsiCache\") session = self.args.get('session') if session",
"for route, verbs in paths.items(): #each http verb in a path for verb,",
"caching auth -- EsiAuth to use for authorized calls to ESI retries --",
"note: loop will be useless if set with session, set the loop you",
"-- Url to the swagger spec Keyword arguments: user_agent -- user agent to",
"None: param_details = param.copy() else: param_details = self.__get_ref(path) param_name = param_details.get(\"name\") new_op[\"parameters\"][param_name] =",
"operation.get(\"parameters\") new_op[\"parameters\"] = {} for param in params: path = param.get(\"$ref\") if path",
"session(self): session = EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get base url",
"aiohttp ClientSession\") self.operations = {} self.data = {} r = requests.get(swagger_url) try: data",
"arguments: user_agent -- user agent to send with ESI calls cache -- EsiCache",
"'w') as esifile: esifile.write(r.text) return finally: r.close() self.data = data self.__analyze_swagger() def session(self):",
"path): path_split = path.split(\"/\") if path_split[0] != \"#\": #Unsupported return None ref =",
"must be a aiohttp ClientSession\") self.operations = {} self.data = {} r =",
"except: logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json', 'w') as esifile: esifile.write(r.text)",
"use for caching auth -- EsiAuth to use for authorized calls to ESI",
"data = r.json() except: logger.exception(\"Parse error, spec written to file\") with open('esi-spec-error.json', 'w')",
"Initialize the class Arguments: swagger_url -- Url to the swagger spec Keyword arguments:",
"path = param.get(\"$ref\") if path is None: param_details = param.copy() else: param_details =",
"{} for param in params: path = param.get(\"$ref\") if path is None: param_details",
"instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if cache is not",
"logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates \"EsiOp\" operations based on a",
"returns a retryable error, 0 disables, -1 is unlimited loop -- Event loop",
"a retryable error, 0 disables, -1 is unlimited loop -- Event loop to",
"= EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get base url self.base_url =",
"#Get base url self.base_url = \"https://\" + self.data.get(\"host\",\"\") + self.data.get(\"basePath\", \"\") #Reformat json",
"the session instead \"\"\" self.args = kwargs cache = kwargs.get(\"cache\", DictCache()) if cache",
"DictCache from .esisession import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\"",
"when ESI returns a retryable error, 0 disables, -1 is unlimited loop --",
"EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class creates",
"#Unsupported return None ref = self.data for i in range(1, len(path_split)): ref =",
"self.operations = {} self.data = {} r = requests.get(swagger_url) try: data = r.json()",
"= kwargs.get(\"cache\", DictCache()) if cache is not None: if not issubclass(type(cache), EsiCache): raise",
"on a provided swagger spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the",
"aiohttp import requests import json from .op import EsiOp from .auth import EsiAuth",
"session = EsiSession(self.base_url, self.operations, **self.args) return session def __analyze_swagger(self): #Get base url self.base_url",
"self.data = {} r = requests.get(swagger_url) try: data = r.json() except: logger.exception(\"Parse error,",
"to use for authorized calls to ESI retries -- Number of retries when",
"set the loop you want in the session instead \"\"\" self.args = kwargs",
"route, verbs in paths.items(): #each http verb in a path for verb, operation",
"use for authorized calls to ESI retries -- Number of retries when ESI",
"session, set the loop you want in the session instead \"\"\" self.args =",
"#each path for route, verbs in paths.items(): #each http verb in a path",
"verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None: continue new_op = operation.copy() new_op[\"path\"]",
"from .cache import EsiCache, DictCache from .esisession import EsiSession import logging logger =",
"spec \"\"\" def __init__(self, swagger_url, **kwargs): \"\"\" Initialize the class Arguments: swagger_url --",
"import EsiAuth from .cache import EsiCache, DictCache from .esisession import EsiSession import logging",
"for caching auth -- EsiAuth to use for authorized calls to ESI retries",
"json paths = self.data.get(\"paths\", {}) #each path for route, verbs in paths.items(): #each",
"object to use for caching auth -- EsiAuth to use for authorized calls",
"import EsiSession import logging logger = logging.getLogger(\"EsiPysi\") class EsiPysi(object): \"\"\" The EsiPysi class",
"useless if set with session, set the loop you want in the session",
"= param_details.get(\"name\") new_op[\"parameters\"][param_name] = param_details self.operations[operation_id] = new_op def __get_ref(self, path): path_split =",
"if operation_id is None: continue new_op = operation.copy() new_op[\"path\"] = route new_op[\"verb\"] =",
"\"#\": #Unsupported return None ref = self.data for i in range(1, len(path_split)): ref",
"not issubclass(type(cache), EsiCache): raise TypeError(\"cache should be of the type EsiCache\") session =",
"operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None: continue new_op =",
"TypeError(\"cache should be of the type EsiCache\") session = self.args.get('session') if session is",
"path for verb, operation in verbs.items(): operation_id = operation.get(\"operationId\") if operation_id is None:",
"= param.get(\"$ref\") if path is None: param_details = param.copy() else: param_details = self.__get_ref(path)",
"for authorized calls to ESI retries -- Number of retries when ESI returns",
"the swagger spec Keyword arguments: user_agent -- user agent to send with ESI"
] |
[] |
[
"<filename>Part 1/Chapter 4/example 1.1.py<gh_stars>0 score = 92 print(\"优秀\") if score >= 90 else",
"print(\"优秀\") if score >= 90 else print(\"及格\") a = 1 b = 2",
"1.1.py<gh_stars>0 score = 92 print(\"优秀\") if score >= 90 else print(\"及格\") a =",
">= 90 else print(\"及格\") a = 1 b = 2 print(type(a)) print(type(b)) print(a/b)",
"if score >= 90 else print(\"及格\") a = 1 b = 2 print(type(a))",
"= 92 print(\"优秀\") if score >= 90 else print(\"及格\") a = 1 b",
"1/Chapter 4/example 1.1.py<gh_stars>0 score = 92 print(\"优秀\") if score >= 90 else print(\"及格\")",
"score = 92 print(\"优秀\") if score >= 90 else print(\"及格\") a = 1",
"4/example 1.1.py<gh_stars>0 score = 92 print(\"优秀\") if score >= 90 else print(\"及格\") a",
"score >= 90 else print(\"及格\") a = 1 b = 2 print(type(a)) print(type(b))",
"92 print(\"优秀\") if score >= 90 else print(\"及格\") a = 1 b ="
] |
[
"- Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer =",
"utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt'",
"Kota Factory - EP 01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def",
"utils import sys path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01",
"i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext)",
"r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01 - Inventory - YouTube.srt' output_file_name",
"and English only cannot be checked at the same time') sys.exit(0) elif chinese_only:",
"01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer",
"chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n')",
"YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs",
"Factory - EP 01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path,",
"english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if",
"English only cannot be checked at the same time') sys.exit(0) elif chinese_only: chinese_lines=[]",
"% (output_file_name), chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' %",
"english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt'",
"be checked at the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in",
"i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for i",
"path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01 - Inventory -",
"for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name),",
"chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked at the",
"for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for",
"import utils import sys path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP",
"range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)):",
"range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext) timer.stop() print('提取完成,用时%.2f秒'",
"and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked at",
"timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only == True:",
"= r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01 - Inventory - YouTube.srt'",
"sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines)",
"utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and",
"extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs)",
"= utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only",
"chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[]",
"(webm)/(English)(499) Kota Factory - EP 01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path)",
"if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be",
"= utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path)",
"sys path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01 - Inventory",
"only and English only cannot be checked at the same time') sys.exit(0) elif",
"output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs =",
"in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext) timer.stop()",
"chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only",
"utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext",
"<filename>core/extract_plain_text.py import utils import sys path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory -",
"- YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start()",
"only cannot be checked at the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for",
"Factory (webm)/(English)(499) Kota Factory - EP 01 - Inventory - YouTube.srt' output_file_name =",
"import sys path = r'/Users/caosheng/Downloads/Kota Factory (webm)/(English)(499) Kota Factory - EP 01 -",
"def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext =",
"chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only:",
"utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext) timer.stop() print('提取完成,用时%.2f秒' % (timer.elapsed))",
"utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only ==",
"cannot be checked at the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i",
"at the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n')",
"= utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only",
"plaintext = utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English",
"in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif english_only: english_lines=[] for i in",
"print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked at the same time') sys.exit(0)",
"== True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked at the same",
"checked at the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)):",
"= utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only",
"% (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext) timer.stop() print('提取完成,用时%.2f秒' % (timer.elapsed)) extract_plain_text(path)",
"Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False): timer = utils.Timer()",
"chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines)",
"elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), chinese_lines) elif",
"(output_file_name), chinese_lines) elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name),",
"time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name),",
"english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' %",
"elif english_only: english_lines=[] for i in range(len(plaintext)): english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else:",
"True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked at the same time')",
"english_lines.append(utils.english_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' % (output_file_name), english_lines) else: utils.write_lines('%s.txt' % (output_file_name), plaintext) timer.stop() print('提取完成,用时%.2f秒' %",
"same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt' %",
"english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot be checked",
"EP 01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False, chinese_only=False):",
"subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese",
"- EP 01 - Inventory - YouTube.srt' output_file_name = utils.get_filename(path) def extract_plain_text(path, english_only=False,",
"the same time') sys.exit(0) elif chinese_only: chinese_lines=[] for i in range(len(plaintext)): chinese_lines.append(utils.chinese_only(plaintext[i])+'\\n') utils.write_lines('%s.txt'",
"timer = utils.Timer() timer.start() subs = utils.load_sub_file(path) plaintext = utils.get_plaintext(subs) if english_only and",
"utils.get_plaintext(subs) if english_only and chinese_only == True: print('仅保留中文和仅保留英文不能同时勾选\\nChinese only and English only cannot"
] |
[
"GPIO from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True:",
"as GPIO from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while",
"GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17, GPIO.LOW)",
"GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17, GPIO.LOW) sleep(1.5) except KeyboardInterrupt:",
"import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5)",
"from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17,",
"# GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17, GPIO.LOW) sleep(1.5) except KeyboardInterrupt: GPIO.cleanup();",
"try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17, GPIO.LOW) sleep(1.5)",
"GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17, GPIO.LOW) sleep(1.5) except",
"import RPi.GPIO as GPIO from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) #",
"RPi.GPIO as GPIO from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17",
"time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH)",
"<gh_stars>0 import RPi.GPIO as GPIO from time import sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT)",
"sleep GPIO.setmode(g.BCM) try: GPIO.setup(17, GPIO.OUT) # GPIO17 while True: GPIO.output(17, GPIO.HIGH) sleep(1.5) GPIO.output(17,"
] |
[
"# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import",
"the active branch name and the current project's root path\"\"\" repo = get_repo()",
"import os from git import Repo def get_repo(): \"\"\"Returns the Repo of the",
"None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name",
"get_repo(): \"\"\"Returns the Repo of the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir,",
"repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name and the current project's root",
"repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name and",
"of the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns",
"Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the top-level directory of current",
"path to the top-level directory of current project\"\"\" if repo is None: repo",
"Repo of the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None):",
"if repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the",
"def get_project_root(repo=None): \"\"\"Returns the path to the top-level directory of current project\"\"\" if",
"from __future__ import print_function from __future__ import unicode_literals import os from git import",
"from __future__ import unicode_literals import os from git import Repo def get_repo(): \"\"\"Returns",
"Repo def get_repo(): \"\"\"Returns the Repo of the current directory\"\"\" call_dir = os.getcwd()",
"os from git import Repo def get_repo(): \"\"\"Returns the Repo of the current",
"from git import Repo def get_repo(): \"\"\"Returns the Repo of the current directory\"\"\"",
"return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name and the current project's",
"import print_function from __future__ import unicode_literals import os from git import Repo def",
"unicode_literals import os from git import Repo def get_repo(): \"\"\"Returns the Repo of",
"get_branch_and_root(): \"\"\"Returns the active branch name and the current project's root path\"\"\" repo",
"from __future__ import division from __future__ import print_function from __future__ import unicode_literals import",
"active branch name and the current project's root path\"\"\" repo = get_repo() root",
"the Repo of the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def",
"import division from __future__ import print_function from __future__ import unicode_literals import os from",
"print_function from __future__ import unicode_literals import os from git import Repo def get_repo():",
"return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the top-level directory of",
"top-level directory of current project\"\"\" if repo is None: repo = get_repo() return",
"name and the current project's root path\"\"\" repo = get_repo() root = get_project_root(repo)",
"get_project_root(repo=None): \"\"\"Returns the path to the top-level directory of current project\"\"\" if repo",
"get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name and the current",
"repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active",
"import absolute_import from __future__ import division from __future__ import print_function from __future__ import",
"absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals",
"the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the",
"import Repo def get_repo(): \"\"\"Returns the Repo of the current directory\"\"\" call_dir =",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function from",
"os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the top-level directory",
"\"\"\"Returns the path to the top-level directory of current project\"\"\" if repo is",
"directory of current project\"\"\" if repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\")",
"the current project's root path\"\"\" repo = get_repo() root = get_project_root(repo) return repo.active_branch.name,",
"import unicode_literals import os from git import Repo def get_repo(): \"\"\"Returns the Repo",
"and the current project's root path\"\"\" repo = get_repo() root = get_project_root(repo) return",
"to the top-level directory of current project\"\"\" if repo is None: repo =",
"directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to",
"is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch",
"\"\"\"Returns the active branch name and the current project's root path\"\"\" repo =",
"__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__",
"division from __future__ import print_function from __future__ import unicode_literals import os from git",
"def get_repo(): \"\"\"Returns the Repo of the current directory\"\"\" call_dir = os.getcwd() return",
"current project's root path\"\"\" repo = get_repo() root = get_project_root(repo) return repo.active_branch.name, root",
"current project\"\"\" if repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root():",
"__future__ import print_function from __future__ import unicode_literals import os from git import Repo",
"current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path",
"git import Repo def get_repo(): \"\"\"Returns the Repo of the current directory\"\"\" call_dir",
"<reponame>CalgaryMichael/branchdb-python # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__",
"of current project\"\"\" if repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def",
"the top-level directory of current project\"\"\" if repo is None: repo = get_repo()",
"__future__ import unicode_literals import os from git import Repo def get_repo(): \"\"\"Returns the",
"def get_branch_and_root(): \"\"\"Returns the active branch name and the current project's root path\"\"\"",
"search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the top-level directory of current project\"\"\"",
"= os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the top-level",
"branch name and the current project's root path\"\"\" repo = get_repo() root =",
"\"\"\"Returns the Repo of the current directory\"\"\" call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True)",
"call_dir = os.getcwd() return Repo(call_dir, search_parent_directories=True) def get_project_root(repo=None): \"\"\"Returns the path to the",
"__future__ import division from __future__ import print_function from __future__ import unicode_literals import os",
"coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"= get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns the active branch name and the",
"project\"\"\" if repo is None: repo = get_repo() return repo.git.rev_parse(u\"--show-toplevel\") def get_branch_and_root(): \"\"\"Returns",
"the path to the top-level directory of current project\"\"\" if repo is None:"
] |
[
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See the same file in the",
"copyright notice and this permission notice shall be included in all copies or",
"TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload,",
"in the nextcord folder for more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"a copy of this software and associated documentation files (the \"Software\"), to deal",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"permission notice shall be included in all copies or substantial portions of the",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"to permit persons to whom the Software is furnished to do so, subject",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is hereby granted, free of charge,",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"License (MIT) Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is hereby",
"Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log,",
"_WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading, time, urlquote, utils, ) __all__",
"this software and associated documentation files (the \"Software\"), to deal in the Software",
"the following conditions: The above copyright notice and this permission notice shall be",
"conditions: The above copyright notice and this permission notice shall be included in",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"free of charge, to any person obtaining a copy of this software and",
"and this permission notice shall be included in all copies or substantial portions",
"Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook,",
"and to permit persons to whom the Software is furnished to do so,",
"_get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading, time, urlquote,",
"See the same file in the nextcord folder for more information Autogenerated by",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re,",
"furnished to do so, subject to the following conditions: The above copyright notice",
"be included in all copies or substantial portions of the Software. THE SOFTWARE",
"Copyright (c) 2021-present tag-epic Permission is hereby granted, free of charge, to any",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar,",
"moodule. See the same file in the nextcord folder for more information Autogenerated",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple,",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased",
"whom the Software is furnished to do so, subject to the following conditions:",
"permit persons to whom the Software is furnished to do so, subject to",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"the Software without restriction, including without limitation the rights to use, copy, modify,",
"any person obtaining a copy of this software and associated documentation files (the",
"person obtaining a copy of this software and associated documentation files (the \"Software\"),",
"the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List,",
"_log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading, time, urlquote, utils,",
"copies of the Software, and to permit persons to whom the Software is",
"without restriction, including without limitation the rights to use, copy, modify, merge, publish,",
"merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See",
"Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is hereby granted, free",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"the nextcord folder for more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"included in all copies or substantial portions of the Software. THE SOFTWARE IS",
"Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json,",
"for more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING,",
"associated documentation files (the \"Software\"), to deal in the Software without restriction, including",
"Aliased moodule. See the same file in the nextcord folder for more information",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule.",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and",
"THE SOFTWARE. -------------- Aliased moodule. See the same file in the nextcord folder",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument,",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext,",
"IN THE SOFTWARE. -------------- Aliased moodule. See the same file in the nextcord",
"The MIT License (MIT) Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"notice shall be included in all copies or substantial portions of the Software.",
"in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"the Software, and to permit persons to whom the Software is furnished to",
"information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook,",
"annotations, handle_message_parameters, json, logging, overload, re, threading, time, urlquote, utils, ) __all__ =",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"-------------- Aliased moodule. See the same file in the nextcord folder for more",
"sublicense, and/or sell copies of the Software, and to permit persons to whom",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"this permission notice shall be included in all copies or substantial portions of",
"same file in the nextcord folder for more information Autogenerated by aliasgen.py \"\"\"",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to",
"following conditions: The above copyright notice and this permission notice shall be included",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"(c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is hereby granted, free of",
"\"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden,",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"(MIT) Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is hereby granted,",
"distribute, sublicense, and/or sell copies of the Software, and to permit persons to",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"copy of this software and associated documentation files (the \"Software\"), to deal in",
"software and associated documentation files (the \"Software\"), to deal in the Software without",
"copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"_WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading, time, urlquote, utils, )",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"\"\"\" The MIT License (MIT) Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"The above copyright notice and this permission notice shall be included in all",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"notice and this permission notice shall be included in all copies or substantial",
"obtaining a copy of this software and associated documentation files (the \"Software\"), to",
"shall be included in all copies or substantial portions of the Software. THE",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any,",
"charge, to any person obtaining a copy of this software and associated documentation",
"\"Software\"), to deal in the Software without restriction, including without limitation the rights",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"2021-present tag-epic Permission is hereby granted, free of charge, to any person obtaining",
"deal in the Software without restriction, including without limitation the rights to use,",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"granted, free of charge, to any person obtaining a copy of this software",
"limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging,",
"List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union,",
"tag-epic Permission is hereby granted, free of charge, to any person obtaining a",
"the Software is furnished to do so, subject to the following conditions: The",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"the same file in the nextcord folder for more information Autogenerated by aliasgen.py",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message,",
"of this software and associated documentation files (the \"Software\"), to deal in the",
"from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException,",
"publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See the same file",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"sell copies of the Software, and to permit persons to whom the Software",
"persons to whom the Software is furnished to do so, subject to the",
"subject to the following conditions: The above copyright notice and this permission notice",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading,",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See the",
"json, logging, overload, re, threading, time, urlquote, utils, ) __all__ = (\"SyncWebhook\", \"SyncWebhookMessage\")",
"Software is furnished to do so, subject to the following conditions: The above",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError,",
"folder for more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING,",
"Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context,",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"do so, subject to the following conditions: The above copyright notice and this",
"handle_message_parameters, json, logging, overload, re, threading, time, urlquote, utils, ) __all__ = (\"SyncWebhook\",",
"by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict,",
"is hereby granted, free of charge, to any person obtaining a copy of",
"all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"and associated documentation files (the \"Software\"), to deal in the Software without restriction,",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter,",
"(c) 2021-present tag-epic Permission is hereby granted, free of charge, to any person",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import ( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock,",
"to deal in the Software without restriction, including without limitation the rights to",
"SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations,",
"is furnished to do so, subject to the following conditions: The above copyright",
"SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters,",
"SOFTWARE. -------------- Aliased moodule. See the same file in the nextcord folder for",
"hereby granted, free of charge, to any person obtaining a copy of this",
"Rapptz Copyright (c) 2021-present tag-epic Permission is hereby granted, free of charge, to",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"nextcord folder for more information Autogenerated by aliasgen.py \"\"\" from nextcord.webhook.sync import (",
"to whom the Software is furnished to do so, subject to the following",
"documentation files (the \"Software\"), to deal in the Software without restriction, including without",
"files (the \"Software\"), to deal in the Software without restriction, including without limitation",
"Software without restriction, including without limitation the rights to use, copy, modify, merge,",
"so, subject to the following conditions: The above copyright notice and this permission",
"restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,",
"_context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState, annotations, handle_message_parameters, json, logging, overload, re, threading, time,",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"to do so, subject to the following conditions: The above copyright notice and",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"to the following conditions: The above copyright notice and this permission notice shall",
"DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage,",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"Software, and to permit persons to whom the Software is furnished to do",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter, _context, _get_webhook_adapter, _log, _WebhookContext, _WebhookState,",
"in the Software without restriction, including without limitation the rights to use, copy,",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"MIT License (MIT) Copyright (c) 2015-present Rapptz Copyright (c) 2021-present tag-epic Permission is",
"DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route,",
"of the Software, and to permit persons to whom the Software is furnished",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable,",
"and/or sell copies of the Software, and to permit persons to whom the",
"to any person obtaining a copy of this software and associated documentation files",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See the same file in",
"( MISSING, TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal,",
"above copyright notice and this permission notice shall be included in all copies",
"HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type,",
"file in the nextcord folder for more information Autogenerated by aliasgen.py \"\"\" from",
"Literal, Message, NotFound, Optional, PartialMessageable, Route, SyncWebhook, SyncWebhookMessage, Tuple, Type, TypeVar, Union, WebhookAdapter,",
"USE OR OTHER DEALINGS IN THE SOFTWARE. -------------- Aliased moodule. See the same",
"of charge, to any person obtaining a copy of this software and associated",
"(the \"Software\"), to deal in the Software without restriction, including without limitation the",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"TYPE_CHECKING, Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound,",
"Any, BaseWebhook, DeferredLock, Dict, DiscordServerError, Forbidden, HTTPException, InvalidArgument, List, Literal, Message, NotFound, Optional,"
] |
[
"code'): print('log: %s' % (data, )) else: player.quit() def init_player(): # Don't autospawn",
"loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad if __name__ == '__main__':",
"run the asyncore event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad",
"the asyncore event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad if",
"# play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad = init_cad()",
"% (data, )) else: player.quit() def init_player(): # Don't autospawn because we want",
"cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3')",
"a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn()",
"MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {}",
"or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event):",
"in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event loop asyncore.loop()",
"''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8):",
"def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate()",
"= player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad)",
"stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn() # play a file",
"init_player(): # Don't autospawn because we want to setup the args later player",
"player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3')",
"import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log: %s' % (data, ))",
"mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log: %s' % (data,",
"the args later player = AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet',",
"not data.startswith('EOF code'): print('log: %s' % (data, )) else: player.quit() def init_player(): #",
"def handle_data(data): if not data.startswith('EOF code'): print('log: %s' % (data, )) else: player.quit()",
"listener.activate() # run the asyncore event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD()",
"player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def",
"{name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in",
"AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log: %s' % (data, )) else:",
"= ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) #",
"setup the args later player = AsyncPlayer(autospawn=False) # Setup additional args player.args =",
"(data, )) else: player.quit() def init_player(): # Don't autospawn because we want to",
"print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run",
"process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad",
"from mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log: %s' %",
"listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event loop asyncore.loop() def init_cad():",
"range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event loop asyncore.loop() def",
"later player = AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6']",
"player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener",
"for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event",
"player = AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] #",
"asyncore event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad if __name__",
"player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad =",
")) else: player.quit() def init_player(): # Don't autospawn because we want to setup",
"# hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer",
"autospawn because we want to setup the args later player = AsyncPlayer(autospawn=False) #",
"file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', '')))",
"metadata = player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener =",
"['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually",
"pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next)",
"if not data.startswith('EOF code'): print('log: %s' % (data, )) else: player.quit() def init_player():",
"i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event loop",
"the MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or",
"# run the asyncore event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return",
"init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for",
"a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title',",
"to setup the args later player = AsyncPlayer(autospawn=False) # Setup additional args player.args",
"AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a",
"{} cad = init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num))",
"subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn() #",
"play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata or {} cad = init_cad() cad.lcd.write('P:",
"additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to MPlayer's",
"event loop asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad if __name__ ==",
"= pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE,",
"Manually spawn the MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata =",
"# for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore",
"def init_player(): # Don't autospawn because we want to setup the args later",
"player.quit() def init_player(): # Don't autospawn because we want to setup the args",
"asyncore.loop() def init_cad(): cad = pifacecad.PiFaceCAD() return cad if __name__ == '__main__': init_player()",
"play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() #",
"to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn() # play",
"handle_data(data): if not data.startswith('EOF code'): print('log: %s' % (data, )) else: player.quit() def",
"spawn the MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata = player.metadata",
"%s' % (data, )) else: player.quit() def init_player(): # Don't autospawn because we",
"player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0, pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the",
"listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i in range(8): listener.register(0,",
"else: player.quit() def init_player(): # Don't autospawn because we want to setup the",
"Don't autospawn because we want to setup the args later player = AsyncPlayer(autospawn=False)",
"import pifacecad import asyncore from mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF",
"'global=6'] # hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the",
"player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data)",
"we want to setup the args later player = AsyncPlayer(autospawn=False) # Setup additional",
"print('log: %s' % (data, )) else: player.quit() def init_player(): # Don't autospawn because",
"# Manually spawn the MPlayer process player.spawn() # play a file player.loadfile('/home/pi/y.mp3') metadata",
"# Don't autospawn because we want to setup the args later player =",
"MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process player.spawn() # play a",
"pifacecad.IODIR_FALLING_EDGE, play_next) listener.activate() # run the asyncore event loop asyncore.loop() def init_cad(): cad",
"# Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber",
"asyncore from mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log: %s'",
"because we want to setup the args later player = AsyncPlayer(autospawn=False) # Setup",
"hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn the MPlayer process",
"data.startswith('EOF code'): print('log: %s' % (data, )) else: player.quit() def init_player(): # Don't",
"= init_cad() cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') #",
"play_next) listener.activate() # run the asyncore event loop asyncore.loop() def init_cad(): cad =",
"pifacecad import asyncore from mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'):",
"= AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook",
"args later player = AsyncPlayer(autospawn=False) # Setup additional args player.args = ['-really-quiet', '-msglevel',",
"want to setup the args later player = AsyncPlayer(autospawn=False) # Setup additional args",
"cad.lcd.write('P: {name}'.format(name=metadata.get('Title', ''))) listener = pifacecad.SwitchEventListener(chip=cad) def play_next(event): print(str(event.pin_num)) player.loadfile('/home/pi/c.mp3') # for i",
"args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to MPlayer's stdout",
"import asyncore from mplayer.async import AsyncPlayer def handle_data(data): if not data.startswith('EOF code'): print('log:",
"'-msglevel', 'global=6'] # hook a subscriber to MPlayer's stdout player.stdout.hook(handle_data) # Manually spawn",
"Setup additional args player.args = ['-really-quiet', '-msglevel', 'global=6'] # hook a subscriber to"
] |
[
"import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui import XeroInterfaceUI __version__ = '2.4.2'",
"Xero. \"\"\" # import package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import",
"# import package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from",
"\"\"\"A set of functions to retrieve and save data into Xero. \"\"\" #",
"import package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui",
"i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui import XeroInterfaceUI __version__ =",
"retrieve and save data into Xero. \"\"\" # import package modules from i_xero2.i_xero",
"\"\"\" # import package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface",
"from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui import XeroInterfaceUI __version__",
"into Xero. \"\"\" # import package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero",
"and save data into Xero. \"\"\" # import package modules from i_xero2.i_xero import",
"modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui import XeroInterfaceUI",
"save data into Xero. \"\"\" # import package modules from i_xero2.i_xero import ExpiredCredentialsException",
"to retrieve and save data into Xero. \"\"\" # import package modules from",
"package modules from i_xero2.i_xero import ExpiredCredentialsException from i_xero2.i_xero import XeroInterface from i_xero2.i_xero_ui import",
"functions to retrieve and save data into Xero. \"\"\" # import package modules",
"data into Xero. \"\"\" # import package modules from i_xero2.i_xero import ExpiredCredentialsException from",
"of functions to retrieve and save data into Xero. \"\"\" # import package",
"set of functions to retrieve and save data into Xero. \"\"\" # import"
] |
[
"# Calculate LID on sample using the estimation from [1] # [1] Ma",
"import torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using the estimation",
"from [1] # [1] Ma et al., \"Characterizing Adversarial Subspaces Using # Local",
"= inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i",
"distance if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k,",
"when using cosine distance if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else:",
"compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using the estimation from [1] [1]",
"Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0),",
"enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs,",
"input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim",
"Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x =",
"when using cosine distance # if exclude_self: # topk_dist = dist.topk(k + 1,",
"# return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0)",
"batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total",
"batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for l, layer in enumerate(layers): y",
"# lid[i] = -1 / mean_log # return lid def compute_spnorm(inputs, dknn, layers,",
"lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm =",
"jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size,",
"= (x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest` should be True when",
"= torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm",
"\"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" #",
"-1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in",
"et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with",
"np import torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using the",
"lid = torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist = (x_cur.view(1, -1)",
"= np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin,",
"1) # `largest` should be True when using cosine distance if exclude_self: topk_dist",
"i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :]",
":return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output =",
"# if exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else: #",
"distance # if exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else:",
"(i + 1) * batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for l,",
"= reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\"",
"y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param output:",
"batch_size)) for i in range(num_batches): begin, end = i * batch_size, (i +",
"# topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i]",
"in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] =",
"output.size(1), input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0]",
"using cosine distance if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist",
"largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid",
"compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers)))",
"norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs:",
"reps = dknn.get_activations(x) for l, layer in enumerate(layers): y = reps[layer] norm[begin:end, l]",
"# Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x = x.view((x.size(0), -1))",
"# `largest` should be True when using cosine distance if exclude_self: topk_dist =",
"torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2,",
"exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist =",
"torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm =",
"x_train, k, exclude_self=False): \"\"\" Calculate LID using the estimation from [1] [1] Ma",
"Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1))",
"for i, x_cur in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1) #",
"should be True when using cosine distance if exclude_self: topk_dist = dist.topk(k +",
"lid[i] = -1 / mean_log return lid # def cal_class_lid(x, x_train, k, exclude_self=False):",
"the estimation from [1] # [1] Ma et al., \"Characterizing Adversarial Subspaces Using",
"topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 /",
"(x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should be True when using cosine",
"jacobian[:, i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i in",
"et al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018. #",
"else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() #",
"Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x =",
"estimation from [1] # [1] Ma et al., \"Characterizing Adversarial Subspaces Using #",
"Using # Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x = x.view((x.size(0),",
"num_batches = int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin, end = i",
"in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should be",
"i, x_cur in enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2, 1) #",
"1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i]",
"# [1] Ma et al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\"",
"range(num_batches): begin, end = i * batch_size, (i + 1) * batch_size x",
"* batch_size, (i + 1) * batch_size x = inputs[begin:end] reps = dknn.get_activations(x)",
"mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid #",
"= inputs[begin:end] reps = dknn.get_activations(x) for l, layer in enumerate(layers): y = reps[layer]",
"mean_log return lid # def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate",
"lid # def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate LID on",
"x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i, x_cur",
"def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate LID on sample using",
":param inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size)",
"x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist =",
"should be True when using cosine distance # if exclude_self: # topk_dist =",
"= -1 / mean_log # return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert",
"+ 1) * batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for l, layer",
"inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size))",
"Ma et al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018.",
"dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist /",
"x_cur in enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # #",
"topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0]",
"using the estimation from [1] [1] Ma et al., \"Characterizing Adversarial Subspaces Using",
"(batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size,",
"for i, x_cur in enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2, 1)",
"= dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1",
"= int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin, end = i *",
"largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] =",
"for l, layer in enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y)",
"k, exclude_self=False): \"\"\" Calculate LID using the estimation from [1] [1] Ma et",
"al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\"",
"output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad =",
"= np.zeros((batch_size, )) for i in range(batch_size): norm[i] = np.linalg.norm(jacobian[i].detach().cpu().numpy(), 2) return norm",
"inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i",
"# x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) # for i,",
"with torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0),",
"dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log return",
"estimation from [1] [1] Ma et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic",
"+ 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean()",
"True when using cosine distance if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:]",
"i * batch_size, (i + 1) * batch_size x = inputs[begin:end] reps =",
"[1] Ma et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018.",
"return lid # def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate LID",
"i in range(num_batches): begin, end = i * batch_size, (i + 1) *",
"Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x = x.view((x.size(0), -1)) # x_train",
"from [1] [1] Ma et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\"",
"end = i * batch_size, (i + 1) * batch_size x = inputs[begin:end]",
"= i * batch_size, (i + 1) * batch_size x = inputs[begin:end] reps",
"topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log =",
"-1)) # x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) # for",
"torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x): # dist = (x_cur.view(1, -1)",
"output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output",
"= grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i in range(batch_size): norm[i] =",
"for i in range(num_batches): begin, end = i * batch_size, (i + 1)",
"True when using cosine distance # if exclude_self: # topk_dist = dist.topk(k +",
"x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i, x_cur in enumerate(x):",
"= x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist",
"-1) - x_train).norm(2, 1) # `largest` should be True when using cosine distance",
"batch_size, (i + 1) * batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for",
"-1 / mean_log return lid # def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\"",
"1) # # `largest` should be True when using cosine distance # if",
"ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1))",
"Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x",
"be True when using cosine distance # if exclude_self: # topk_dist = dist.topk(k",
"topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] =",
"/ mean_log # return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total",
"Ma et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\"",
"dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest` should be True",
"# for i, x_cur in enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2,",
"len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin, end =",
"2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid",
"x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) #",
"inputs[begin:end] reps = dknn.get_activations(x) for l, layer in enumerate(layers): y = reps[layer] norm[begin:end,",
"= x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) # for i, x_cur in",
"i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i in range(batch_size):",
"al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad():",
"i, x_cur in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest`",
"- x_train).norm(2, 1) # # `largest` should be True when using cosine distance",
":param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim =",
"= (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should be True when using",
"inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for",
"x_cur in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should",
"torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs,",
"\"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x",
"Dimensionality,\" ICLR 2018. # \"\"\" # x = x.view((x.size(0), -1)) # x_train =",
"x_train, k, exclude_self=False): # \"\"\" # Calculate LID on sample using the estimation",
"np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin, end",
"dknn.get_activations(x) for l, layer in enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x,",
"-1)) lid = torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist = (x_cur.view(1,",
"range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size,",
"= torch.zeros((x.size(0), )) for i, x_cur in enumerate(x): dist = (x_cur.view(1, -1) -",
"norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size, output_size)",
"= torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 / mean_log # return lid",
"[1] Ma et al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic Dimensionality,\" ICLR",
"in enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest`",
"reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param",
"jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad( output[:,",
"\"\"\" # Calculate LID on sample using the estimation from [1] # [1]",
"lid[i] = -1 / mean_log # return lid def compute_spnorm(inputs, dknn, layers, batch_size=200):",
"= compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size)",
"# \"\"\" # x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) #",
"largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist /",
"-1 / mean_log # return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad",
"torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid # def cal_class_lid(x,",
")) for i, x_cur in enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1)",
"1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist",
"else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1",
"in enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def",
"= torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(),",
"x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0),",
"= x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), ))",
"- x_train).norm(2, 1) # `largest` should be True when using cosine distance if",
"exclude_self=False): # \"\"\" # Calculate LID on sample using the estimation from [1]",
"input_dim) norm = np.zeros((batch_size, )) for i in range(batch_size): norm[i] = np.linalg.norm(jacobian[i].detach().cpu().numpy(), 2)",
"if exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist",
"= output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad",
"lid = torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x): # dist =",
"(batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size()",
"output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0),",
"= dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log",
"the estimation from [1] [1] Ma et al., \"Characterizing Adversarial Subspaces Using Local",
"= x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i,",
"largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 / mean_log",
"\"\"\" Calculate LID using the estimation from [1] [1] Ma et al., \"Characterizing",
"if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0]",
"sample using the estimation from [1] # [1] Ma et al., \"Characterizing Adversarial",
"2018. # \"\"\" # x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1))",
"k, exclude_self=False): # \"\"\" # Calculate LID on sample using the estimation from",
"# x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) # lid =",
"# else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean()",
"return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm",
"output): \"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size,",
":] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i in range(batch_size): norm[i]",
"output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size,",
")) # for i, x_cur in enumerate(x): # dist = (x_cur.view(1, -1) -",
"topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid # def cal_class_lid(x, x_train, k,",
"+ 1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log =",
"# mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 / mean_log #",
"`largest` should be True when using cosine distance if exclude_self: topk_dist = dist.topk(k",
"\"\"\" # x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0), -1)) # lid",
"dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should be True when",
"LID on sample using the estimation from [1] # [1] Ma et al.,",
"dist.topk(k, largest=False)[0] # mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 /",
"1) * batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for l, layer in",
"x_train = x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) # for i, x_cur",
"l, layer in enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return",
"for i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i,",
"i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, ))",
"# # `largest` should be True when using cosine distance # if exclude_self:",
"# topk_dist = dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k,",
"output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian",
"/ mean_log return lid # def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" #",
"norm = np.zeros((batch_size, )) for i in range(batch_size): norm[i] = np.linalg.norm(jacobian[i].detach().cpu().numpy(), 2) return",
"= dknn.get_activations(x) for l, layer in enumerate(layers): y = reps[layer] norm[begin:end, l] =",
"= torch.log(topk_dist / topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid # def",
"dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches",
"assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total /",
"int(np.ceil(num_total / batch_size)) for i in range(num_batches): begin, end = i * batch_size,",
"x = inputs[begin:end] reps = dknn.get_activations(x) for l, layer in enumerate(layers): y =",
"/ topk_dist[-1]).mean() # lid[i] = -1 / mean_log # return lid def compute_spnorm(inputs,",
"/ topk_dist[-1]).mean() lid[i] = -1 / mean_log return lid # def cal_class_lid(x, x_train,",
"enumerate(x): # dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest` should",
"[1] [1] Ma et al., \"Characterizing Adversarial Subspaces Using Local Intrinsic Dimensionality,\" ICLR",
"x_train.view((x_train.size(0), -1)) # lid = torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x):",
"\"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size,",
"\"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size,",
"[1] # [1] Ma et al., \"Characterizing Adversarial Subspaces Using # Local Intrinsic",
"* batch_size x = inputs[begin:end] reps = dknn.get_activations(x) for l, layer in enumerate(layers):",
"x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for",
"inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i in",
"x_train).norm(2, 1) # `largest` should be True when using cosine distance if exclude_self:",
"grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i in range(batch_size): norm[i] = np.linalg.norm(jacobian[i].detach().cpu().numpy(),",
"Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0),",
"-1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad(",
"cosine distance if exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist =",
"# def cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate LID on sample",
"Calculate LID on sample using the estimation from [1] # [1] Ma et",
"Local Intrinsic Dimensionality,\" ICLR 2018. # \"\"\" # x = x.view((x.size(0), -1)) #",
"input_dim)) for i in range(output.size(1)): grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:,",
"Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train =",
"LID using the estimation from [1] [1] Ma et al., \"Characterizing Adversarial Subspaces",
"torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using the estimation from",
"l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size,",
"x_train).norm(2, 1) # # `largest` should be True when using cosine distance #",
"torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 / mean_log # return lid def",
"input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim))",
"on sample using the estimation from [1] # [1] Ma et al., \"Characterizing",
"exclude_self=False): \"\"\" Calculate LID using the estimation from [1] [1] Ma et al.,",
"in range(num_batches): begin, end = i * batch_size, (i + 1) * batch_size",
"layer in enumerate(layers): y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm",
"cosine distance # if exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:] #",
"= torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x): # dist = (x_cur.view(1,",
"def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total,",
"-1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), )) for i, x_cur in",
"mean_log = torch.log(topk_dist / topk_dist[-1]).mean() # lid[i] = -1 / mean_log # return",
"norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for i in range(num_batches):",
"= inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for",
"as np import torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using",
"\"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid =",
"= -1 / mean_log return lid # def cal_class_lid(x, x_train, k, exclude_self=False): #",
"retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim) norm = np.zeros((batch_size, )) for i",
"-1)) # lid = torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x): #",
"cal_class_lid(x, x_train, k, exclude_self=False): # \"\"\" # Calculate LID on sample using the",
"num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches = int(np.ceil(num_total / batch_size)) for",
"def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID using the estimation from [1]",
"(x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest` should be True when using",
"Local Intrinsic Dimensionality,\" ICLR 2018. \"\"\" with torch.no_grad(): x = x.view((x.size(0), -1)) x_train",
"= dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0] #",
"# `largest` should be True when using cosine distance # if exclude_self: #",
"layers, batch_size=200): assert inputs.requires_grad num_total = inputs.size(0) norm = np.zeros((num_total, len(layers))) num_batches =",
"-1) - x_train).norm(2, 1) # # `largest` should be True when using cosine",
"dist.topk(k + 1, largest=False)[0][1:] # else: # topk_dist = dist.topk(k, largest=False)[0] # mean_log",
"= dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log = torch.log(topk_dist",
"compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param",
"begin, end = i * batch_size, (i + 1) * batch_size x =",
"topk_dist[-1]).mean() # lid[i] = -1 / mean_log # return lid def compute_spnorm(inputs, dknn,",
"mean_log # return lid def compute_spnorm(inputs, dknn, layers, batch_size=200): assert inputs.requires_grad num_total =",
"using cosine distance # if exclude_self: # topk_dist = dist.topk(k + 1, largest=False)[0][1:]",
"output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1), input_dim)) for i in range(output.size(1)):",
"exclude_self: topk_dist = dist.topk(k + 1, largest=False)[0][1:] else: topk_dist = dist.topk(k, largest=False)[0] mean_log",
"y = reps[layer] norm[begin:end, l] = compute_spnorm_batch(x, y) return norm def compute_spnorm_batch(inputs, output):",
"grad = torch.autograd.grad( output[:, i].sum(), inputs, retain_graph=True)[0] jacobian[:, i, :] = grad.view(batch_size, input_dim)",
"return norm def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size,",
"# dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # # `largest` should be",
"/ batch_size)) for i in range(num_batches): begin, end = i * batch_size, (i",
"batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian = torch.zeros((batch_size, output.size(1),",
"# lid = torch.zeros((x.size(0), )) # for i, x_cur in enumerate(x): # dist",
"input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1) jacobian =",
"using the estimation from [1] # [1] Ma et al., \"Characterizing Adversarial Subspaces",
"torch.no_grad(): x = x.view((x.size(0), -1)) x_train = x_train.view((x_train.size(0), -1)) lid = torch.zeros((x.size(0), ))",
"numpy as np import torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate LID",
"Calculate LID using the estimation from [1] [1] Ma et al., \"Characterizing Adversarial",
"be True when using cosine distance if exclude_self: topk_dist = dist.topk(k + 1,",
"enumerate(x): dist = (x_cur.view(1, -1) - x_train).norm(2, 1) # `largest` should be True",
"# \"\"\" # Calculate LID on sample using the estimation from [1] #",
"ICLR 2018. # \"\"\" # x = x.view((x.size(0), -1)) # x_train = x_train.view((x_train.size(0),",
"compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian:",
"inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return: jacobian: (batch_size, output_size, input_size) \"\"\"",
"def compute_spnorm_batch(inputs, output): \"\"\" :param inputs: (batch_size, input_size) :param output: (batch_size, output_size) :return:",
"(batch_size, output_size, input_size) \"\"\" batch_size, input_dim = inputs.view(inputs.size(0), -1).size() output = output.view(batch_size, -1)",
"`largest` should be True when using cosine distance # if exclude_self: # topk_dist",
"import numpy as np import torch def compute_lid(x, x_train, k, exclude_self=False): \"\"\" Calculate"
] |
[
"@abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self):",
"name(self): assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self): assert False",
"@abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self):",
"assert False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception): def __init__(self, message): Exception.__init__(self,",
"@abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self):",
"False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception): def __init__(self, message): Exception.__init__(self, message)",
"False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def",
"def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert",
"False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def",
"def name(self): assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self): assert",
"Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod",
"False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def",
"def close(self): assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self): assert",
"def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception): def __init__(self,",
"assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod",
"with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self): assert",
"object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def",
"def open(self): assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert",
"False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def",
"class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self): assert False",
"open(self): assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False",
"assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod",
"@abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self):",
"getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception): def __init__(self, message):",
"def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert",
"@abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception): def",
"abc from six import with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False",
"import with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def close(self):",
"close(self): assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod def isClosed(self): assert False",
"six import with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod def",
"assert False @abc.abstractmethod def close(self): assert False @abc.abstractmethod def open(self): assert False @abc.abstractmethod",
"performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False",
"False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False class LoopException(Exception):",
"import abc from six import with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert",
"@abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self):",
"isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False",
"assert False @abc.abstractmethod def isClosed(self): assert False @abc.abstractmethod def performOnePass(self): assert False @abc.abstractmethod",
"assert False @abc.abstractmethod def getConvergenceStepCount(self): assert False @abc.abstractmethod def hasConverged(self): assert False class",
"from six import with_metaclass class Loop(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def name(self): assert False @abc.abstractmethod"
] |
[
"import io import numpy as np import seaborn as sns import matplotlib.pyplot as",
"import matplotlib.pyplot as plt from PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14,",
"import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\")",
"plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO() plt.savefig(buff, format='jpg') buff.seek(0) return np.array(Image.open(buff))",
"matplotlib.pyplot as plt from PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6))",
"xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO() plt.savefig(buff,",
"import seaborn as sns import matplotlib.pyplot as plt from PIL import Image def",
"source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout()",
"np import seaborn as sns import matplotlib.pyplot as plt from PIL import Image",
"<gh_stars>1-10 import io import numpy as np import seaborn as sns import matplotlib.pyplot",
"seaborn as sns import matplotlib.pyplot as plt from PIL import Image def alphaPlot(alpha,",
"alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60)",
"numpy as np import seaborn as sns import matplotlib.pyplot as plt from PIL",
"PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05,",
"io import numpy as np import seaborn as sns import matplotlib.pyplot as plt",
"cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO() plt.savefig(buff, format='jpg') buff.seek(0) return",
"import numpy as np import seaborn as sns import matplotlib.pyplot as plt from",
"as sns import matplotlib.pyplot as plt from PIL import Image def alphaPlot(alpha, output,",
"as plt from PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha,",
"Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source')",
"def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target')",
"plt from PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(),",
"plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff",
"6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff =",
"yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO() plt.savefig(buff, format='jpg')",
"linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO() plt.savefig(buff, format='jpg') buff.seek(0)",
"from PIL import Image def alphaPlot(alpha, output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(),",
"sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0) plt.tight_layout() buff = io.BytesIO()",
"output, source): plt.figure(figsize=(14, 6)) sns.heatmap(alpha, xticklabels=output.split(), yticklabels=source.split(), linewidths=.05, cmap=\"Blues\") plt.ylabel('Source') plt.xlabel('Target') plt.xticks(rotation=60) plt.yticks(rotation=0)",
"sns import matplotlib.pyplot as plt from PIL import Image def alphaPlot(alpha, output, source):",
"as np import seaborn as sns import matplotlib.pyplot as plt from PIL import"
] |
[
"on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField(",
"verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name",
"SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} - Grade:",
"= models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name",
"Grade: {self.grade}\" def clean(self) -> None: \"\"\" This method checks whether the teacher",
"to be assigned to the class is working in that school. \"\"\" if",
"models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\",",
"the teacher trying to be assigned to the class is working in that",
"max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural =",
"school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor",
"class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def",
"name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name =",
"= SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} -",
"import ValidationError from constants.school_strings import SchoolStrings from django.db import models from school.models.abstract_base_model import",
"verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name}",
"ValidationError from constants.school_strings import SchoolStrings from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel",
"from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name)",
"= SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name}",
"def __str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self) -> None:",
"\"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name =",
"verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural",
"import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor =",
"\"\"\" This method checks whether the teacher trying to be assigned to the",
"- {self.name} - Grade: {self.grade}\" def clean(self) -> None: \"\"\" This method checks",
"models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField(",
"clean(self) -> None: \"\"\" This method checks whether the teacher trying to be",
"= [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def",
"trying to be assigned to the class is working in that school. \"\"\"",
"-> None: \"\"\" This method checks whether the teacher trying to be assigned",
"ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\"",
"{self.grade}\" def clean(self) -> None: \"\"\" This method checks whether the teacher trying",
"verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name)",
"class is working in that school. \"\"\" if self.instructor.school != self.school: raise ValidationError(SchoolStrings.ClassStrings.instructor_not_working_at_this_school_error)",
"\"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name)",
"related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta:",
"= models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering =",
"None: \"\"\" This method checks whether the teacher trying to be assigned to",
"from django.core.exceptions import ValidationError from constants.school_strings import SchoolStrings from django.db import models from",
"[\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self)",
"= models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade =",
"django.core.exceptions import ValidationError from constants.school_strings import SchoolStrings from django.db import models from school.models.abstract_base_model",
"instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade",
"class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\",",
"__str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self) -> None: \"\"\"",
"<reponame>talhakoylu/SummerInternshipBackend from django.core.exceptions import ValidationError from constants.school_strings import SchoolStrings from django.db import models",
"from constants.school_strings import SchoolStrings from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class",
"Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self):",
"constants.school_strings import SchoolStrings from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel):",
"method checks whether the teacher trying to be assigned to the class is",
"be assigned to the class is working in that school. \"\"\" if self.instructor.school",
"AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey(",
"the class is working in that school. \"\"\" if self.instructor.school != self.school: raise",
"return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self) -> None: \"\"\" This",
"SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return f\"{self.school.name} -",
"- Grade: {self.grade}\" def clean(self) -> None: \"\"\" This method checks whether the",
"school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\",",
"from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey(",
"on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class",
"related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50,",
"whether the teacher trying to be assigned to the class is working in",
"SchoolStrings from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school =",
"django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\",",
"This method checks whether the teacher trying to be assigned to the class",
"models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural",
"def clean(self) -> None: \"\"\" This method checks whether the teacher trying to",
"{self.name} - Grade: {self.grade}\" def clean(self) -> None: \"\"\" This method checks whether",
"assigned to the class is working in that school. \"\"\" if self.instructor.school !=",
"models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name",
"checks whether the teacher trying to be assigned to the class is working",
"teacher trying to be assigned to the class is working in that school.",
"Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE,",
"to the class is working in that school. \"\"\" if self.instructor.school != self.school:",
"f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self) -> None: \"\"\" This method",
"\"grade\"] def __str__(self): return f\"{self.school.name} - {self.name} - Grade: {self.grade}\" def clean(self) ->",
"= models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( \"account.InstructorProfile\", on_delete=models.CASCADE, related_name=\"instructors_school\", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name)",
"import SchoolStrings from django.db import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school",
"models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE, related_name=\"classes_school\",",
"import models from school.models.abstract_base_model import AbstractSchoolBaseModel class Class(AbstractSchoolBaseModel): school = models.ForeignKey( \"school.School\", on_delete=models.CASCADE,",
"verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"] def __str__(self): return",
"verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering = [\"name\", \"grade\"]",
"grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) class Meta: verbose_name = SchoolStrings.ClassStrings.meta_verbose_name verbose_name_plural = SchoolStrings.ClassStrings.meta_verbose_name_plural ordering"
] |
[
"coding:utf-8 -*- # author:Agam # datetime:2018-11-05 from flask import Blueprint admin=Blueprint('admin',__name__) import app.admin.views",
"#-*- coding:utf-8 -*- # author:Agam # datetime:2018-11-05 from flask import Blueprint admin=Blueprint('admin',__name__) import",
"<filename>app/admin/__init__.py #-*- coding:utf-8 -*- # author:Agam # datetime:2018-11-05 from flask import Blueprint admin=Blueprint('admin',__name__)"
] |
[
"<filename>cstorage/tests/listen-gcs.py #!/usr/bin/env python from google.cloud import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo'",
"pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name)",
"from google.cloud import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub'",
"import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription =",
"= 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message message.ack()",
"sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message message.ack() future =",
"'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message message.ack() future = subscription.open(callback) future.result()",
"google.cloud import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription",
"sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def",
"= pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message):",
"'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message message.ack() future",
"= 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message message.ack() future = subscription.open(callback)",
"pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print",
"#!/usr/bin/env python from google.cloud import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name",
"python from google.cloud import pubsub_v1 sub = pubsub_v1.SubscriberClient() #topic = 'project/skippbox/topics/barfoo' sub_name =",
"#topic = 'project/skippbox/topics/barfoo' sub_name = 'projects/skippbox/subscriptions/carogoasub' subscription = sub.subscribe(sub_name) def callback(message): print message"
] |
[
"'w') out = \"const IR = Object.freeze({\\n\" k = 0 for op in",
"script to automatically generate code # since Javascript doesn't have enums and using",
"opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out = \"const IR =",
"0 for op in opcodes: out += f\"\\t{op}: {k},\\n\" k += 1 out",
"return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports = {IR, irToString}; \"\"\"",
"start_if close_if_body end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var",
"= re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\"",
"= \"\"\" pop_ push_ inc dec add sub equals set_var get_var inc_n false_",
"+= \"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for op in opcodes: out",
"helper script to automatically generate code # since Javascript doesn't have enums and",
"have enums and using objects as \\ # enums is painful. import re",
"generate code # since Javascript doesn't have enums and using objects as \\",
"enums and using objects as \\ # enums is painful. import re IR",
"op in opcodes: out += f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\"",
"automatically generate code # since Javascript doesn't have enums and using objects as",
"opcodes: out += f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\" out +=",
"push_ inc dec add sub equals set_var get_var inc_n false_ true_ load_byte print",
"set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out",
"and using objects as \\ # enums is painful. import re IR =",
"len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out = \"const",
"k = 0 for op in opcodes: out += f\"\\t{op}: {k},\\n\" k +=",
"+= \"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for op",
"= open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\" k = 0 for",
"<gh_stars>1-10 # This is a helper script to automatically generate code # since",
"since Javascript doesn't have enums and using objects as \\ # enums is",
"{k},\\n\" k += 1 out += \"});\\n\\n\" out += \"\"\" function irToString(op) {",
"code # since Javascript doesn't have enums and using objects as \\ #",
"opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\"",
"false_ true_ load_byte print start_if close_if_body end_if start_else end_else start_loop end_loop popn cmp_less",
"\"\"\" pop_ push_ inc dec add sub equals set_var get_var inc_n false_ true_",
"pop_ push_ inc dec add sub equals set_var get_var inc_n false_ true_ load_byte",
"= Object.freeze({\\n\" k = 0 for op in opcodes: out += f\"\\t{op}: {k},\\n\"",
"\\tswitch(op) { \"\"\" for op in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\"",
"IR = Object.freeze({\\n\" k = 0 for op in opcodes: out += f\"\\t{op}:",
"out += f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\" out += \"\"\"",
"out = \"const IR = Object.freeze({\\n\" k = 0 for op in opcodes:",
"objects as \\ # enums is painful. import re IR = \"\"\" pop_",
"load_byte print start_if close_if_body end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string",
"\"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out = \"const IR",
"popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input len \"\"\" opcodes",
"k += 1 out += \"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op)",
"\"\"\" for op in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out +=",
"as \\ # enums is painful. import re IR = \"\"\" pop_ push_",
"enums is painful. import re IR = \"\"\" pop_ push_ inc dec add",
"+= 1 out += \"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op) {",
"start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index",
"not make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js',",
"end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input",
"true_ load_byte print start_if close_if_body end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater",
"make_bus index_var not make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile",
"This is a helper script to automatically generate code # since Javascript doesn't",
"# enums is painful. import re IR = \"\"\" pop_ push_ inc dec",
"function irToString(op) { \\tswitch(op) { \"\"\" for op in opcodes: out += f\"\\tcase",
"irToString(op) { \\tswitch(op) { \"\"\" for op in opcodes: out += f\"\\tcase IR.{op}:",
"{ \\tswitch(op) { \"\"\" for op in opcodes: out += f\"\\tcase IR.{op}: return",
"using objects as \\ # enums is painful. import re IR = \"\"\"",
"re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\" k",
"f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports = {IR,",
"inc_n false_ true_ load_byte print start_if close_if_body end_if start_else end_else start_loop end_loop popn",
"print start_if close_if_body end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus",
"equals set_var get_var inc_n false_ true_ load_byte print start_if close_if_body end_if start_else end_else",
"close_if_body end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var not",
"is a helper script to automatically generate code # since Javascript doesn't have",
"IR) irFile = open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\" k =",
"\"const IR = Object.freeze({\\n\" k = 0 for op in opcodes: out +=",
"a helper script to automatically generate code # since Javascript doesn't have enums",
"make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w')",
"irFile = open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\" k = 0",
"dec add sub equals set_var get_var inc_n false_ true_ load_byte print start_if close_if_body",
"# This is a helper script to automatically generate code # since Javascript",
"sub equals set_var get_var inc_n false_ true_ load_byte print start_if close_if_body end_if start_else",
"import re IR = \"\"\" pop_ push_ inc dec add sub equals set_var",
"\\ # enums is painful. import re IR = \"\"\" pop_ push_ inc",
"= 0 for op in opcodes: out += f\"\\t{op}: {k},\\n\" k += 1",
"f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\" out += \"\"\" function irToString(op)",
"Object.freeze({\\n\" k = 0 for op in opcodes: out += f\"\\t{op}: {k},\\n\" k",
"+= f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\" out += \"\"\" function",
"in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out +=",
"Javascript doesn't have enums and using objects as \\ # enums is painful.",
"\"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for op in",
"for op in opcodes: out += f\"\\t{op}: {k},\\n\" k += 1 out +=",
"end_if start_else end_else start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus",
"set_var get_var inc_n false_ true_ load_byte print start_if close_if_body end_if start_else end_else start_loop",
"1 out += \"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op) { \"\"\"",
"out += \"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for op in opcodes:",
"add sub equals set_var get_var inc_n false_ true_ load_byte print start_if close_if_body end_if",
"cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input len \"\"\" opcodes =",
"for op in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\"",
"op in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out",
"painful. import re IR = \"\"\" pop_ push_ inc dec add sub equals",
"to automatically generate code # since Javascript doesn't have enums and using objects",
"open('../src/ir.js', 'w') out = \"const IR = Object.freeze({\\n\" k = 0 for op",
"end_loop popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input len \"\"\"",
"in opcodes: out += f\"\\t{op}: {k},\\n\" k += 1 out += \"});\\n\\n\" out",
"# since Javascript doesn't have enums and using objects as \\ # enums",
"IR = \"\"\" pop_ push_ inc dec add sub equals set_var get_var inc_n",
"out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports",
"load_string make_bus index_var not make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR)",
"re IR = \"\"\" pop_ push_ inc dec add sub equals set_var get_var",
"{ \"\"\" for op in opcodes: out += f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out",
"'{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports = {IR, irToString}; \"\"\" irFile.write(out)",
"out += \"});\\n\\n\" out += \"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for",
"+= f\"\\tcase IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports =",
"cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\",",
"IR.{op}: return '{op.upper()}';\\n\" out += \"\\t}\\n}\" out += \"\"\" module.exports = {IR, irToString};",
"= \"const IR = Object.freeze({\\n\" k = 0 for op in opcodes: out",
"\"\"\" function irToString(op) { \\tswitch(op) { \"\"\" for op in opcodes: out +=",
"start_loop end_loop popn cmp_less cmp_greater load_string make_bus index_var not make_sized_bus set_at_index input len",
"doesn't have enums and using objects as \\ # enums is painful. import",
"is painful. import re IR = \"\"\" pop_ push_ inc dec add sub",
"inc dec add sub equals set_var get_var inc_n false_ true_ load_byte print start_if",
"input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile = open('../src/ir.js', 'w') out =",
"index_var not make_sized_bus set_at_index input len \"\"\" opcodes = re.findall(r\"\\w+\", IR) irFile =",
"get_var inc_n false_ true_ load_byte print start_if close_if_body end_if start_else end_else start_loop end_loop"
] |
[
"are assigned NaN in the new column). :returns: A pandas DataFrame. \"\"\" #",
"be passed into `DataFrame.groupby`. :param new_column_name: Name of the aggregation output column. :param",
"9, 9, 9], ... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\",",
"... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count",
"x y y_count 0 a 9 2 1 a 9 2 2 None",
"agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count 0",
"2 None 9 1 3 b 9 1 :param df: A pandas DataFrame.",
"A pandas DataFrame. :param by: Column(s) to groupby on, will be passed into",
"str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna: bool = True, )",
") item quantity avg_quantity 0 shoe 100 140.0 1 shoe 120 140.0 2",
"df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... )",
"200 140.0 4 bag 25 50.0 Example: Set `dropna=False` to compute the aggregation,",
"9 2 2 None 9 1 3 b 9 1 :param df: A",
"... ) item quantity avg_quantity 0 shoe 100 140.0 1 shoe 120 140.0",
"item quantity avg_quantity 0 shoe 100 140.0 1 shoe 120 140.0 2 bag",
"True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a new column.",
"for assigning a groupby-transform to a new column. This method does not mutate",
"does not mutate the original DataFrame. Intended to be the method-chaining equivalent of:",
"pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def",
"will be passed into `DataFrame.groupby`. :param new_column_name: Name of the aggregation output column.",
"import pandas_flavor as pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method",
">>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\":",
">>> import janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\",",
"df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100,",
"groupby on, will be passed into `DataFrame.groupby`. :param new_column_name: Name of the aggregation",
"9 1 3 b 9 1 :param df: A pandas DataFrame. :param by:",
"new column). :returns: A pandas DataFrame. \"\"\" # noqa: E501 return df.assign( **{",
"treating the null values in the `by` column as an isolated \"group\". >>>",
"pandas_flavor as pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\",",
"None, \"b\"], \"y\": [9, 9, 9, 9], ... }) >>> df.groupby_agg( ... by=\"x\",",
"assigning a groupby-transform to a new column. This method does not mutate the",
"```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas as pd",
"dropna=False, ... ) x y y_count 0 a 9 2 1 a 9",
"DataFrame. :param by: Column(s) to groupby on, will be passed into `DataFrame.groupby`. :param",
"... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ...",
"column). :returns: A pandas DataFrame. \"\"\" # noqa: E501 return df.assign( **{ new_column_name:",
"if present in the `by` column(s). Default is True (null values in `by`",
"mutate the original DataFrame. Intended to be the method-chaining equivalent of: ```python df",
"df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas as pd >>>",
"... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200,",
"import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg(",
"Set `dropna=False` to compute the aggregation, treating the null values in the `by`",
"Example: Set `dropna=False` to compute the aggregation, treating the null values in the",
"agg_column_name: Name of the column to aggregate over. :param agg: How to aggregate.",
"... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe 100 140.0 1 shoe",
"deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name:",
"dropna: Whether or not to include null values, if present in the `by`",
"equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas",
">>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item",
"\"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200, 25], ... })",
">>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ...",
"0 shoe 100 140.0 1 shoe 120 140.0 2 bag 75 50.0 3",
"75, 200, 25], ... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\",",
"50.0 Example: Set `dropna=False` to compute the aggregation, treating the null values in",
"}) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False,",
"1 :param df: A pandas DataFrame. :param by: Column(s) to groupby on, will",
"... ) x y y_count 0 a 9 2 1 a 9 2",
"to groupby on, will be passed into `DataFrame.groupby`. :param new_column_name: Name of the",
"agg: How to aggregate. :param dropna: Whether or not to include null values,",
"new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna: bool = True, ) ->",
"present in the `by` column(s). Default is True (null values in `by` are",
"Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna: bool = True,",
"y y_count 0 a 9 2 1 a 9 2 2 None 9",
"[9, 9, 9, 9], ... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ...",
"over. :param agg: How to aggregate. :param dropna: Whether or not to include",
"4 bag 25 50.0 Example: Set `dropna=False` to compute the aggregation, treating the",
"df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas as pd >>> import janitor",
":param by: Column(s) to groupby on, will be passed into `DataFrame.groupby`. :param new_column_name:",
"@pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str,",
"75 50.0 3 shoe 200 140.0 4 bag 25 50.0 Example: Set `dropna=False`",
"import pandas as pd >>> import janitor >>> df = pd.DataFrame({ ... \"x\":",
") x y y_count 0 a 9 2 1 a 9 2 2",
"new_column_name: Name of the aggregation output column. :param agg_column_name: Name of the column",
"b 9 1 :param df: A pandas DataFrame. :param by: Column(s) to groupby",
"in the new column). :returns: A pandas DataFrame. \"\"\" # noqa: E501 return",
"bag 25 50.0 Example: Set `dropna=False` to compute the aggregation, treating the null",
"... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9, 9], ... })",
"janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ...",
"in `by` are assigned NaN in the new column). :returns: A pandas DataFrame.",
"quantity avg_quantity 0 shoe 100 140.0 1 shoe 120 140.0 2 bag 75",
"values in the `by` column as an isolated \"group\". >>> import pandas as",
"NaN in the new column). :returns: A pandas DataFrame. \"\"\" # noqa: E501",
"import Callable, List, Union import pandas_flavor as pf import pandas as pd from",
"9 1 :param df: A pandas DataFrame. :param by: Column(s) to groupby on,",
"= pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9, 9],",
"This method does not mutate the original DataFrame. Intended to be the method-chaining",
"isolated \"group\". >>> import pandas as pd >>> import janitor >>> df =",
"[100, 120, 75, 200, 25], ... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\",",
"2 2 None 9 1 3 b 9 1 :param df: A pandas",
"original DataFrame. Intended to be the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...))",
"by: Column(s) to groupby on, will be passed into `DataFrame.groupby`. :param new_column_name: Name",
"column to aggregate over. :param agg: How to aggregate. :param dropna: Whether or",
"to a new column. This method does not mutate the original DataFrame. Intended",
"null values in the `by` column as an isolated \"group\". >>> import pandas",
"List, Union import pandas_flavor as pf import pandas as pd from janitor.utils import",
"column. :param agg_column_name: Name of the column to aggregate over. :param agg: How",
"import janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\":",
":param dropna: Whether or not to include null values, if present in the",
"(null values in `by` are assigned NaN in the new column). :returns: A",
"import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str],",
"the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>>",
"... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe 100 140.0",
"None 9 1 3 b 9 1 :param df: A pandas DataFrame. :param",
"pandas DataFrame. \"\"\" # noqa: E501 return df.assign( **{ new_column_name: df.groupby(by, dropna=dropna)[ agg_column_name",
"method does not mutate the original DataFrame. Intended to be the method-chaining equivalent",
"`by` column(s). Default is True (null values in `by` are assigned NaN in",
"= df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas as pd >>> import",
"... \"quantity\": [100, 120, 75, 200, 25], ... }) >>> df.groupby_agg( ... by=\"item\",",
"from typing import Callable, List, Union import pandas_flavor as pf import pandas as",
"aggregation output column. :param agg_column_name: Name of the column to aggregate over. :param",
"dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to",
"-> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a new column. This method",
"Name of the aggregation output column. :param agg_column_name: Name of the column to",
":param agg_column_name: Name of the column to aggregate over. :param agg: How to",
"or not to include null values, if present in the `by` column(s). Default",
"pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna:",
"Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna: bool =",
"column(s). Default is True (null values in `by` are assigned NaN in the",
":param df: A pandas DataFrame. :param by: Column(s) to groupby on, will be",
"into `DataFrame.groupby`. :param new_column_name: Name of the aggregation output column. :param agg_column_name: Name",
"aggregation, treating the null values in the `by` column as an isolated \"group\".",
"120, 75, 200, 25], ... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ...",
"`dropna=False` to compute the aggregation, treating the null values in the `by` column",
"pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by:",
"is True (null values in `by` are assigned NaN in the new column).",
"usage. >>> import pandas as pd >>> import janitor >>> df = pd.DataFrame({",
"3 shoe 200 140.0 4 bag 25 50.0 Example: Set `dropna=False` to compute",
"a new column. This method does not mutate the original DataFrame. Intended to",
"\"b\"], \"y\": [9, 9, 9, 9], ... }) >>> df.groupby_agg( ... by=\"x\", ...",
"DataFrame. \"\"\" # noqa: E501 return df.assign( **{ new_column_name: df.groupby(by, dropna=dropna)[ agg_column_name ].transform(agg),",
") -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a new column. This",
"\"group\". >>> import pandas as pd >>> import janitor >>> df = pd.DataFrame({",
"output column. :param agg_column_name: Name of the column to aggregate over. :param agg:",
"Column(s) to groupby on, will be passed into `DataFrame.groupby`. :param new_column_name: Name of",
"= pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120,",
"new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe 100 140.0 1 shoe 120",
"avg_quantity 0 shoe 100 140.0 1 shoe 120 140.0 2 bag 75 50.0",
"as pd >>> import janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\",",
"aggregate over. :param agg: How to aggregate. :param dropna: Whether or not to",
"pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a new column. This method does",
"on, will be passed into `DataFrame.groupby`. :param new_column_name: Name of the aggregation output",
"as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame,",
"140.0 1 shoe 120 140.0 2 bag 75 50.0 3 shoe 200 140.0",
">>> import janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"],",
"the original DataFrame. Intended to be the method-chaining equivalent of: ```python df =",
"df: A pandas DataFrame. :param by: Column(s) to groupby on, will be passed",
"agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count 0 a 9",
"2 1 a 9 2 2 None 9 1 3 b 9 1",
":param agg: How to aggregate. :param dropna: Whether or not to include null",
"@deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name:",
"a 9 2 1 a 9 2 2 None 9 1 3 b",
"# noqa: E501 return df.assign( **{ new_column_name: df.groupby(by, dropna=dropna)[ agg_column_name ].transform(agg), } )",
"How to aggregate. :param dropna: Whether or not to include null values, if",
"9], ... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\",",
"Name of the column to aggregate over. :param agg: How to aggregate. :param",
"of the column to aggregate over. :param agg: How to aggregate. :param dropna:",
"\"\"\" # noqa: E501 return df.assign( **{ new_column_name: df.groupby(by, dropna=dropna)[ agg_column_name ].transform(agg), }",
"of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import pandas as",
"pandas as pd >>> import janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\",",
"of the aggregation output column. :param agg_column_name: Name of the column to aggregate",
"pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df:",
"not mutate the original DataFrame. Intended to be the method-chaining equivalent of: ```python",
"the `by` column(s). Default is True (null values in `by` are assigned NaN",
"140.0 4 bag 25 50.0 Example: Set `dropna=False` to compute the aggregation, treating",
"`DataFrame.groupby`. :param new_column_name: Name of the aggregation output column. :param agg_column_name: Name of",
"the new column). :returns: A pandas DataFrame. \"\"\" # noqa: E501 return df.assign(",
"bag 75 50.0 3 shoe 200 140.0 4 bag 25 50.0 Example: Set",
"3 b 9 1 :param df: A pandas DataFrame. :param by: Column(s) to",
"the aggregation, treating the null values in the `by` column as an isolated",
"from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List,",
"df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str],",
"a 9 2 2 None 9 1 3 b 9 1 :param df:",
"`by` are assigned NaN in the new column). :returns: A pandas DataFrame. \"\"\"",
"... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity",
"compute the aggregation, treating the null values in the `by` column as an",
"\"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200, 25], ... }) >>> df.groupby_agg(",
"1 shoe 120 140.0 2 bag 75 50.0 3 shoe 200 140.0 4",
"1 3 b 9 1 :param df: A pandas DataFrame. :param by: Column(s)",
"shoe 200 140.0 4 bag 25 50.0 Example: Set `dropna=False` to compute the",
"A pandas DataFrame. \"\"\" # noqa: E501 return df.assign( **{ new_column_name: df.groupby(by, dropna=dropna)[",
"to be the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic",
"2 bag 75 50.0 3 shoe 200 140.0 4 bag 25 50.0 Example:",
"str, agg: Union[Callable, str], dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for",
"pd >>> import janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\",",
"agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe 100 140.0 1",
"50.0 3 shoe 200 140.0 4 bag 25 50.0 Example: Set `dropna=False` to",
"Callable, List, Union import pandas_flavor as pf import pandas as pd from janitor.utils",
"aggregate. :param dropna: Whether or not to include null values, if present in",
"an isolated \"group\". >>> import pandas as pd >>> import janitor >>> df",
"by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x y",
"as pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\")",
"bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a",
"def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg:",
"Intended to be the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example:",
"df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9,",
"y_count 0 a 9 2 1 a 9 2 2 None 9 1",
"9 2 1 a 9 2 2 None 9 1 3 b 9",
"include null values, if present in the `by` column(s). Default is True (null",
"25 50.0 Example: Set `dropna=False` to compute the aggregation, treating the null values",
"pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75,",
"}) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... )",
"120 140.0 2 bag 75 50.0 3 shoe 200 140.0 4 bag 25",
"... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count 0 a",
"method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage. >>> import",
"`by` column as an isolated \"group\". >>> import pandas as pd >>> import",
"null values, if present in the `by` column(s). Default is True (null values",
"typing import Callable, List, Union import pandas_flavor as pf import pandas as pd",
"= True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform to a new",
"a groupby-transform to a new column. This method does not mutate the original",
"in the `by` column(s). Default is True (null values in `by` are assigned",
"Default is True (null values in `by` are assigned NaN in the new",
"be the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ``` Example: Basic usage.",
"new column. This method does not mutate the original DataFrame. Intended to be",
"agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name: str,",
"\"y\": [9, 9, 9, 9], ... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\",",
"str], dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a groupby-transform",
"groupby-transform to a new column. This method does not mutate the original DataFrame.",
"... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ... dropna=False, ... ) x",
"df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity",
"to include null values, if present in the `by` column(s). Default is True",
"Union import pandas_flavor as pf import pandas as pd from janitor.utils import deprecated_alias",
"new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count 0 a 9 2 1",
"the aggregation output column. :param agg_column_name: Name of the column to aggregate over.",
"by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0",
"the column to aggregate over. :param agg: How to aggregate. :param dropna: Whether",
"200, 25], ... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ...",
"100 140.0 1 shoe 120 140.0 2 bag 75 50.0 3 shoe 200",
"agg_column_name: str, agg: Union[Callable, str], dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut",
"shoe 120 140.0 2 bag 75 50.0 3 shoe 200 140.0 4 bag",
"pd >>> import janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None,",
"agg: Union[Callable, str], dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning",
"not to include null values, if present in the `by` column(s). Default is",
"0 a 9 2 1 a 9 2 2 None 9 1 3",
"9, 9], ... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ...",
">>> import pandas as pd >>> import janitor >>> df = pd.DataFrame({ ...",
"Example: Basic usage. >>> import pandas as pd >>> import janitor >>> df",
":param new_column_name: Name of the aggregation output column. :param agg_column_name: Name of the",
"to aggregate over. :param agg: How to aggregate. :param dropna: Whether or not",
"Whether or not to include null values, if present in the `by` column(s).",
"True (null values in `by` are assigned NaN in the new column). :returns:",
"\"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200, 25],",
"assigned NaN in the new column). :returns: A pandas DataFrame. \"\"\" # noqa:",
"groupby_agg( df: pd.DataFrame, by: Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable,",
"import janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"],",
"[\"shoe\", \"shoe\", \"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200, 25], ...",
"janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9,",
"\"bag\", \"shoe\", \"bag\"], ... \"quantity\": [100, 120, 75, 200, 25], ... }) >>>",
"pandas DataFrame. :param by: Column(s) to groupby on, will be passed into `DataFrame.groupby`.",
"values, if present in the `by` column(s). Default is True (null values in",
"140.0 2 bag 75 50.0 3 shoe 200 140.0 4 bag 25 50.0",
"to compute the aggregation, treating the null values in the `by` column as",
"import pandas as pd >>> import janitor >>> df = pd.DataFrame({ ... \"item\":",
"``` Example: Basic usage. >>> import pandas as pd >>> import janitor >>>",
"... }) >>> df.groupby_agg( ... by=\"x\", ... agg=\"count\", ... agg_column_name=\"y\", ... new_column_name=\"y_count\", ...",
"1 a 9 2 2 None 9 1 3 b 9 1 :param",
">>> df = pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9,",
"Union[Callable, str], dropna: bool = True, ) -> pd.DataFrame: \"\"\"Shortcut for assigning a",
"\"bag\"], ... \"quantity\": [100, 120, 75, 200, 25], ... }) >>> df.groupby_agg( ...",
"column as an isolated \"group\". >>> import pandas as pd >>> import janitor",
"\"\"\"Shortcut for assigning a groupby-transform to a new column. This method does not",
"str, agg_column_name: str, agg: Union[Callable, str], dropna: bool = True, ) -> pd.DataFrame:",
"by: Union[List, Callable, str], new_column_name: str, agg_column_name: str, agg: Union[Callable, str], dropna: bool",
"passed into `DataFrame.groupby`. :param new_column_name: Name of the aggregation output column. :param agg_column_name:",
"Basic usage. >>> import pandas as pd >>> import janitor >>> df =",
"DataFrame. Intended to be the method-chaining equivalent of: ```python df = df.assign(...=df.groupby(...)[...].transform(...)) ```",
"25], ... }) >>> df.groupby_agg( ... by=\"item\", ... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\",",
"as an isolated \"group\". >>> import pandas as pd >>> import janitor >>>",
"as pd >>> import janitor >>> df = pd.DataFrame({ ... \"item\": [\"shoe\", \"shoe\",",
"[\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9, 9], ... }) >>> df.groupby_agg(",
"the null values in the `by` column as an isolated \"group\". >>> import",
":returns: A pandas DataFrame. \"\"\" # noqa: E501 return df.assign( **{ new_column_name: df.groupby(by,",
"pandas as pd >>> import janitor >>> df = pd.DataFrame({ ... \"x\": [\"a\",",
"... agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe",
"shoe 100 140.0 1 shoe 120 140.0 2 bag 75 50.0 3 shoe",
"the `by` column as an isolated \"group\". >>> import pandas as pd >>>",
"pd.DataFrame({ ... \"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9, 9], ...",
"\"x\": [\"a\", \"a\", None, \"b\"], \"y\": [9, 9, 9, 9], ... }) >>>",
"... dropna=False, ... ) x y y_count 0 a 9 2 1 a",
"values in `by` are assigned NaN in the new column). :returns: A pandas",
"agg=\"mean\", ... agg_column_name=\"quantity\", ... new_column_name=\"avg_quantity\", ... ) item quantity avg_quantity 0 shoe 100",
"... new_column_name=\"y_count\", ... dropna=False, ... ) x y y_count 0 a 9 2",
"in the `by` column as an isolated \"group\". >>> import pandas as pd",
"to aggregate. :param dropna: Whether or not to include null values, if present",
"\"a\", None, \"b\"], \"y\": [9, 9, 9, 9], ... }) >>> df.groupby_agg( ...",
"\"quantity\": [100, 120, 75, 200, 25], ... }) >>> df.groupby_agg( ... by=\"item\", ...",
"column. This method does not mutate the original DataFrame. Intended to be the",
"janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(new_column=\"new_column_name\", agg_column=\"agg_column_name\") def groupby_agg( df: pd.DataFrame, by: Union[List, Callable,"
] |
[
"codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if",
"\"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as e: logger.error(e) raise e",
"response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn:",
"config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\")",
"pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response",
"PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response)",
"response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]:",
"ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\":",
"job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn",
"raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters",
"{\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result",
"logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10,",
"continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"]",
"= os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"})",
") return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, )",
"logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as",
"{pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status =",
"is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response =",
"import Config from botocore.exceptions import ClientError import json import os import logging LOG_LEVEL",
") return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message",
"logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\",",
"], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline",
"f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn )",
"SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response)",
"\"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return",
"from botocore.exceptions import ClientError import json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\",",
"{ \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result)",
"{job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e:",
"logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client =",
"202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"]",
"= { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id,",
"None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution(",
"LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\":",
"= job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn",
"e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message)",
"{job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker",
"return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message =",
"= None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id,",
"{pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response",
"import json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger()",
"{pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\",",
"codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code",
"as e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data",
"result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, }",
"Config from botocore.exceptions import ClientError import json import os import logging LOG_LEVEL =",
"ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info(",
") if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline",
"from botocore.config import Config from botocore.exceptions import ClientError import json import os import",
"in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id,",
"PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" )",
"{pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\",",
") logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if",
"codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = {",
"ClientError import json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger =",
"= { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id,",
"job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info(",
"code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except",
"except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = {",
"error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as e: logger.error(e)",
") logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking",
"os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline",
"return 500, result except Exception as e: logger.error(e) raise e def lambda_handler(event, context):",
"\"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result",
") response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker",
"pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job:",
"job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"},",
"\"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn =",
"\"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn,",
"sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info(",
"for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\":",
"config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None:",
"import ClientError import json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger",
") response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline",
"botocore.config import Config from botocore.exceptions import ClientError import json import os import logging",
"Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = {",
"{pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\",",
"= job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result)) return {\"statusCode\": status_code, \"body\":",
"= response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn}",
"{job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ],",
"\"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline =",
"pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for",
"{pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\":",
"try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\"",
"logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client",
"Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status",
"lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name",
"\"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing",
"pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline job:",
"return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status,",
"= boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn",
"pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result)) return {\"statusCode\": status_code,",
"job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if",
"if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as e:",
"pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result",
"error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message,",
"logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job:",
"boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker",
"logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name,",
"\"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result",
"\"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500,",
"pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline:",
"import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config",
"Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id,",
"event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None",
"= Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def",
"= event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn =",
"} logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception",
"if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" )",
"[\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result",
"job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as",
"failureDetails=result) return 500, result except Exception as e: logger.error(e) raise e def lambda_handler(event,",
"user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data:",
"check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline: {pipeline_name}",
"= json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code,",
"\"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline",
"\"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result))",
"result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\":",
"200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202,",
"= boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting",
"\"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker",
"arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\":",
"= { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200,",
"sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\",",
"PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id,",
"in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result)) return",
"else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution(",
"pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in",
"Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\"",
"result except Exception as e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id",
"400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\":",
"\"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try:",
"\"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400,",
"{ \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result",
"pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code",
"= sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn}",
"\"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None):",
"{ \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result)",
"result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return",
"e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data =",
"Exception as e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"]",
"SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[",
"Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn}",
"error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except",
"{\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn",
"response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for",
"jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id,",
"logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"]",
"logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status",
"result = { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\":",
"pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"]",
"context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name =",
"logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"]",
"logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn}",
"pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result(",
"return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return",
"event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in",
"500, result except Exception as e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event))",
"pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError",
"import boto3 from botocore.config import Config from botocore.exceptions import ClientError import json import",
"job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn =",
"codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as e: logger.error(e) raise e def",
"= sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection",
"f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result =",
"Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\")",
"e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code !=",
"Pipeline: {pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\":",
"pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is",
"response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift",
"if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status",
"jobId=job_id, continuationToken=pipeline_execution_arn, ) return 202, {\"PipelineExecutionArn\": pipeline_execution_arn} except ClientError as e: error_code =",
"f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif",
"f\"Starting SageMaker Pipeline: {pipeline_name} for job: {job_id}\" ) response = sm_client.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=f\"codepipeline-{job_id}\",",
"boto3 from botocore.config import Config from botocore.exceptions import ClientError import json import os",
"} codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\")",
"\"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"]",
"boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is",
"= logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\": 10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config)",
"[\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\", \"externalExecutionId\":",
"} codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result =",
"e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\":",
"json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL)",
"started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response =",
"codepipeline.put_job_success_result( jobId=job_id, outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result(",
"logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker",
"as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\",",
"= event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"] pipeline_name = json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\"",
"= response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\",",
"PipelineExecutionDisplayName=f\"codepipeline-{job_id}\", PipelineParameters=[ {\"Name\": \"InputSource\", \"Value\": \"CodePipeline\"}, ], PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, )",
"\"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, } codepipeline.put_job_success_result( jobId=job_id, outputVariables=result )",
"10, \"mode\": \"standard\"}) codepipeline = boto3.client(\"codepipeline\", config=config) sm_client = boto3.client(\"sagemaker\") def check_pipeline(job_id, pipeline_name,",
"def check_pipeline(job_id, pipeline_name, pipeline_execution_arn=None): try: if pipeline_execution_arn is None: logger.info( f\"Starting SageMaker Pipeline:",
"logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn",
"if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn)",
"except Exception as e: logger.error(e) raise e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id =",
"None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name,",
"result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn,",
"import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config = Config(retries={\"max_attempts\":",
"outputVariables=result ) return 200, result logger.info(f\"Continuing code pipeline job: {job_id}\") codepipeline.put_job_success_result( jobId=job_id, continuationToken=pipeline_execution_arn,",
"elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\": pipeline_execution_status, \"PipelineExecutionArn\": pipeline_execution_arn, }",
"arn: {pipeline_execution_arn} started\") else: logger.info( f\"Checking SageMaker Pipeline: {pipeline_execution_arn} for job: {job_id}\" )",
"error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if",
"is {pipeline_execution_status}\", \"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in",
"def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters = job_data[\"actionConfiguration\"][\"configuration\"][\"UserParameters\"]",
"sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"] logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\"",
"job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result)) return {\"statusCode\": status_code, \"body\": json.dumps(result)}",
"json.loads(user_parameters)[\"PipelineName\"] pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result",
"\"externalExecutionId\": pipeline_execution_arn, } codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]:",
"Pipeline: {pipeline_execution_arn} for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status",
"logger.info( f\"SageMaker Pipeline arn: {pipeline_execution_arn} {pipeline_execution_status}\" ) if pipeline_execution_status in [\"Failed\", \"Stopped\"]: result",
"\"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code != \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return",
"= e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message, } logger.error(error_message) if error_code",
"botocore.exceptions import ClientError import json import os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper()",
"os import logging LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\").upper() logger = logging.getLogger() logger.setLevel(LOG_LEVEL) config =",
"<gh_stars>10-100 import boto3 from botocore.config import Config from botocore.exceptions import ClientError import json",
"pipeline_execution_arn} except ClientError as e: error_code = e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result =",
"Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn: {pipeline_execution_arn} started\") else:",
"= e.response[\"Error\"][\"Code\"] error_message = e.response[\"Error\"][\"Message\"] result = { \"type\": \"JobFailed\", \"message\": error_message, }",
"e def lambda_handler(event, context): logger.debug(json.dumps(event)) job_id = event[\"CodePipeline.job\"][\"id\"] job_data = event[\"CodePipeline.job\"][\"data\"] user_parameters =",
"in [\"Failed\", \"Stopped\"]: result = { \"type\": \"JobFailed\", \"message\": f\"Pipeline Status is {pipeline_execution_status}\",",
"pipeline_execution_arn = None if \"continuationToken\" in job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result =",
"job_data: pipeline_execution_arn = job_data[\"continuationToken\"] status_code, result = check_pipeline(job_id, pipeline_name, pipeline_execution_arn) logger.debug(json.dumps(result)) return {\"statusCode\":",
"failureDetails=result) return 400, result elif pipeline_execution_status in [\"Executing\", \"Succeeded\"]: result = { \"Status\":",
"!= \"InvalidJobStateException\": codepipeline.put_job_failure_result(jobId=job_id, failureDetails=result) return 500, result except Exception as e: logger.error(e) raise",
"for job: {job_id}\" ) response = sm_client.describe_pipeline_execution( PipelineExecutionArn=pipeline_execution_arn ) logger.debug(response) pipeline_execution_status = response[\"PipelineExecutionStatus\"]",
"PipelineExecutionDescription=\"SageMaker Drift Detection Pipeline\", ClientRequestToken=job_id, ) logger.debug(response) pipeline_execution_arn = response[\"PipelineExecutionArn\"] logger.info(f\"SageMaker Pipeline arn:"
] |
[
"1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3.",
"= 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force =",
"[0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000",
"import time import numpy as np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver())",
"= [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness =",
"[0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000",
"= [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity =",
"percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset",
"= [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition =",
"example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG",
"[0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13.,",
"[0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000",
"5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7.",
"= [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter =",
"= [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment =",
"Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring import time import",
"example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW():",
"self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0')",
"example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \",",
"= 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass =",
"'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000",
"= 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell =",
"example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW():",
"example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height",
"example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 #",
"= 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment =",
"= [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation =",
"= 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass =",
"self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print",
"'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG",
"-92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000]",
"print 'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max offset unity:",
"0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831]",
"= [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass =",
"',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max offset",
"mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example = optimizationMooring() # Mooring,settings",
"677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111",
"40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574",
"example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth",
"example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force",
"-20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324",
"example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5",
"4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218.",
"= 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment =",
"= 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth =",
"366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452",
"[5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688]",
"example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition",
"[2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05]",
"example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print",
"example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x",
"= 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force =",
"391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time:",
"from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000",
"\"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__ == \"__main__\": #example_218WD_3MW() #example_218WD_6MW()",
"= optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter =",
"print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print",
"example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass =",
"example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness",
"example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__",
"print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity",
"example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7.,",
"= 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type =",
"[13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861",
"'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass",
"0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass",
"self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example):",
"print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__ ==",
"= [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py",
"-72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000]",
"example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force",
"example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment",
"import numpy as np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring')",
"= 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force =",
"example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth",
"example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment",
"SLSQPdriver from mooring import Mooring import time import numpy as np class optimizationMooring(Assembly):",
"example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness",
"example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation",
"offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost",
"= 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt,",
"offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time()",
"example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type",
"def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter:",
"= 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment =",
"example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness",
"# from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG =",
"= 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG =",
"= 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density =",
"self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0')",
"-20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force =",
"sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio",
"example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation",
"[6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.]",
"example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5.,",
"1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent:",
"'--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt =",
"820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time:",
"= time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5",
"example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density",
"[7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.]",
"class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01)",
"698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024",
"example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \",",
"0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492.",
"example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG",
"example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass",
"self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def",
"example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density",
"[1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.]",
"example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density",
"example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density",
"= 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt,",
"from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring import time import numpy",
"self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity <",
"example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity",
"example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\"",
"[40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.]",
"'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example = optimizationMooring() #",
"# variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <=",
"= 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed",
"= 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment =",
"import COBYLAdriver, SLSQPdriver from mooring import Mooring import time import numpy as np",
"= 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment =",
"example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter",
"'min offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total mooring cost:",
"print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time()",
"= 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force =",
"= [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation =",
"'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667]",
"COBYLAdriver, SLSQPdriver from mooring import Mooring import time import numpy as np class",
"example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force",
"3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------'",
"example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\"",
"3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000.",
"= 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment =",
"0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510]",
"= 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring)",
"= 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth =",
"= 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970]",
"example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy =",
"<= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio:",
"142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389",
"example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force",
"as np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1)",
"4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5",
"tt = time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio =",
"5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def",
"= 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type =",
"[0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity",
"= 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment =",
"211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986",
"example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment",
"= 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x =",
"= [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG =",
"= 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078]",
"\" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth =",
"def example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio =",
"example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type",
"0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492.",
"[62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.]",
"35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000]",
"import Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from",
"3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000.",
"= [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20.,",
"= 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force =",
"0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492.",
"example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5.,",
"example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass",
"unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def",
"Mooring import time import numpy as np class optimizationMooring(Assembly): # variables def configure(self):",
"self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity",
"[0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983",
"= 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048]",
"218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy",
"'--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__ == \"__main__\":",
"self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent",
"30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906]",
"[0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13.,",
"Component, Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool from",
"= [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation =",
"5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN'",
"= [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass =",
"example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7.,",
"example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \",",
"Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring",
"time import numpy as np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring())",
"1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring",
"',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth =",
"= 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type =",
"= 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py",
"= 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height =",
"example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass =",
"= [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20.,",
"= [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000",
"= [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity =",
"example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\"",
"import Component, Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool",
"6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio",
"= [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass =",
"= 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height =",
"= 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density =",
"= [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation =",
"[0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7.,",
"diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max",
"example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print",
"print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print",
"example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass",
"[0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass",
"# Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter =",
"= [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20.,",
"np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.)",
"time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example =",
"[13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177",
"= [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter =",
"'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752]",
"import Mooring import time import numpy as np class optimizationMooring(Assembly): # variables def",
"[0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381",
"= 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed",
"unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example",
"[7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000]",
"openmdao.main.api import Component, Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int,",
"7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB",
"openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver",
"4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE'",
"example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass",
"= 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass =",
"45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000]",
"53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070",
"= [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5.,",
"example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force",
"sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter",
"3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000.",
"3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218.",
"example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines",
"= 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass =",
"= 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print",
"example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height",
"example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force",
"[7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.]",
"[183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N'",
"= [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5.,",
"example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation",
"example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter",
"[3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.]",
"= [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter =",
"= 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force =",
"example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth",
"',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle",
"[0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7.,",
"example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height",
"= 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force =",
"47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \"",
"\"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example",
"example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7.,",
"-5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB =",
"32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850]",
"convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import",
"def example_218WD_3MW(): tt = time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13.",
"example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass",
"example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass",
"= time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent =",
"= 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force =",
"Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring import",
"6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------'",
"'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print",
"[1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05]",
"7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if",
"self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope",
"example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5.,",
"numpy as np class optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost')",
"218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036]",
"-5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB =",
"example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type",
"[13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45.",
"23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178",
"1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4.",
"time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent",
"example_218WD_3MW(): tt = time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio",
"= optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0",
"= [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment =",
"example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run()",
"33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422",
"example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x",
"'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000",
"print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time()",
"Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import",
"from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver,",
"4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def",
"< 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print",
"def example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio =",
"-5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force",
"= 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass =",
"time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example =",
"example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment",
"'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass",
"variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.')",
"print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt",
"[8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189]",
"42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543]",
"-5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force",
"= 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density =",
"1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print '--------------example_218WD_3MW------------------'",
"13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3",
"-5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB =",
"9. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN'",
"example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type",
"optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter",
"= 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density =",
"print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt",
"self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity < 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print",
"',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW():",
"example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter",
"= [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition =",
"= 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print",
"'--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt =",
"= 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height =",
"= 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run() print",
"-20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108",
"= [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation =",
"example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass",
"[2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050]",
"-20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force =",
"< 1.0') self.driver.add_constraint('mooring.max_offset_unity < 1.0') def sys_print(example): print 'scope ratio: ',example.scope_ratio print 'pretension",
"# from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass =",
"seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13.",
"118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt, \"",
"5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5.",
"= 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment =",
"127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835",
"= 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type =",
"example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass",
"= 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force =",
"= 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x =",
"= 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines =",
"Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api",
"example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG",
"example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force",
"print 'min offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total mooring",
"37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000]",
"5.0 example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9.",
"print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example = optimizationMooring()",
"example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass",
"-5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force",
"example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter",
"= 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density =",
"example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000 example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity",
"from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass = [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490]",
"example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG",
"-20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337",
"= [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000",
"example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation",
"optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090",
"\", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example = optimizationMooring()",
"example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation",
"',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example =",
"= 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed",
"print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__ == \"__main__\": #example_218WD_3MW()",
"-20., -67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force =",
"example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell",
"ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle:",
"def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity",
"= [40321.556,88041.563,137796.144,518693.048] example.mooring.bulkhead_mass = [0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5.,",
"= 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run() print '--------------example_218WD_6MW------------------' print \"Elapsed time: \", time.time()-tt,",
"= 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring)",
"example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5",
"= [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness =",
"\", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example = optimizationMooring()",
"example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment",
"33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750",
"example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x",
"[100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N'",
"example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print",
"Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0 example.mooring.mooring_diameter = 0.090",
"= 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment =",
"example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment",
"example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 # from,spar.py example.mooring.shell_buoyancy = [0.000,144905.961,688303.315,3064761.078] example.mooring.shell_mass =",
"'heel angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity",
"-67.] example.mooring.spar_keel_to_CG = 35.861 example.mooring.spar_keel_to_CB = 30.324 example.mooring.spar_outer_diameter = [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000]",
"'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min",
"1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time:",
"'scope ratio: ',example.scope_ratio print 'pretension percent: ',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel",
"example.mooring.load_condition = 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG",
"time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent = 5.0",
"[137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N'",
"'max offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt =",
"<gh_stars>1-10 from openmdao.main.api import Component, Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum,",
"example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB = 32.337 example.mooring.spar_outer_diameter = [7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment",
"time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) if __name__ == \"__main__\": #example_218WD_3MW() #example_218WD_6MW() example_218WD_10MW()",
"from openmdao.main.api import Component, Assembly, convert_units from openmdao.main.datatypes.api import Float, Array, Enum, Str,",
"example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition",
"example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1 example.run()",
"example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition",
"from mooring import Mooring import time import numpy as np class optimizationMooring(Assembly): #",
"[55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass = [3838.515,16391.495,21578.677,127137.831] example.mooring.spar_start_elevation = [13., 7., -5., -20.]",
"example.mooring.tower_mass = 698235.000 example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment",
"example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation",
"example.mooring.tower_center_of_gravity = 40.983 example.mooring.RNA_keel_to_CG = 211.000 example.mooring.tower_wind_force = 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force",
"7. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN'",
"= [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation =",
"\"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example",
"[0.000,10730.836,0.000,24417.970] example.mooring.ring_mass = [1245.878,5444.950,6829.259,28747.490] example.mooring.spar_start_elevation = [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7.,",
"= [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' example.mooring.RNA_mass =",
"\" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth =",
"cost: ',example.mooring_total_cost def example_218WD_3MW(): tt = time.time() example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth",
"125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948 example.mooring.RNA_keel_to_CG = 142.000 example.mooring.tower_wind_force = 19950.529",
"example = optimizationMooring() # Mooring,settings example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent =",
"= 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density =",
"314378753.986 example.mooring.RNA_center_of_gravity_x = 7.070 example.run() print '--------------example_218WD_10MW------------------' print \"Elapsed time: \", time.time()-tt, \"",
"[0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment = [0.000,66158450.987,145104271.963,2244211.189] example.mooring.wall_thickness = [0.050,0.050,0.050,0.050] example.mooring.load_condition = 'N' example.mooring.RNA_mass = 677000.000",
"Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring import time",
"optimizationMooring(Assembly): # variables def configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle",
"print 'max offset unity: ',example.max_offset_unity print 'total mooring cost: ',example.mooring_total_cost def example_218WD_3MW(): tt",
"example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density",
"= [5.000,6.000,6.000,9.000] example.mooring.spar_wind_force = [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment =",
"169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187",
"time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth",
"= 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy =",
"example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity =",
"= 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass = 127877.000 example.mooring.tower_center_of_gravity = 23.948",
"[0.000,326038.413,1775098.024,13041536.503] example.mooring.shell_mass = [62516.908,132432.268,221028.715,1335368.667] example.mooring.bulkhead_mass = [0.000,24417.970,0.000,68438.752] example.mooring.ring_mass = [6963.553,29512.202,39460.135,617575.510] example.mooring.spar_start_elevation = [13.,",
"3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth = 218.",
"= 'N' example.mooring.RNA_mass = 365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG =",
"example.mooring.mooring_diameter = 0.090 example.mooring.number_of_mooring_lines = 3 example.mooring.permanent_ballast_height = 4. example.mooring.fixed_ballast_height = 9. example.mooring.permanent_ballast_density",
"configure(self): self.add('driver',COBYLAdriver()) self.add('mooring',Mooring()) self.driver.workflow.add('mooring') self.driver.add_objective('mooring.mooring_total_cost') self.driver.add_parameter('mooring.scope_ratio',low=15.,high=50.,scaler=0.1) self.driver.add_parameter('mooring.pretension_percent',low=2.5,high=20.) self.driver.add_parameter('mooring.mooring_diameter',low=3.,high=10.,scaler=0.01) self.driver.add_constraint('mooring.heel_angle <= 6.') self.driver.add_constraint('mooring.min_offset_unity <",
"angle: ',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print",
"example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment = 118970074.187 example.mooring.RNA_center_of_gravity_x = 5.750 example.run()",
"example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008] example.mooring.ring_mass",
"Float, Array, Enum, Str, Int, Bool from openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring",
"365500.000 example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492",
"= 53037.111 example.mooring.tower_wind_moment = 6112673.024 example.mooring.RNA_wind_force = 1743933.574 example.mooring.RNA_wind_moment = 314378753.986 example.mooring.RNA_center_of_gravity_x =",
"example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment",
"218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,326038.413,1775098.024,13041536.503]",
"example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass =",
"= 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass =",
"example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' #",
"time.time()-tt, \" seconds\" sys_print(example.mooring) def example_218WD_6MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth",
"',example.pretension_percent print 'mooring diameter: ',example.mooring_diameter print 'heel angle: ',example.heel_angle print 'min offset unity:",
"7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG = 45. example.mooring.spar_keel_to_CB",
"= [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -67.] example.mooring.spar_keel_to_CG =",
"tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio = 1.5 example.mooring.pretension_percent",
"',example.heel_angle print 'min offset unity: ',example.min_offset_unity print 'max offset unity: ',example.max_offset_unity print 'total",
"example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force = [0.000,1125719.734,3051908.296,425853.543] example.mooring.spar_current_moment",
"mooring import Mooring import time import numpy as np class optimizationMooring(Assembly): # variables",
"seconds\" sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13.",
"'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783]",
"7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -72.] example.mooring.spar_keel_to_CG = 37.177 example.mooring.spar_keel_to_CB",
"example.mooring.spar_keel_to_CB = 42.108 example.mooring.spar_outer_diameter = [8.,9.,9.,15.] example.mooring.spar_wind_force = [2572.428,2522.369,0.000,0.000] example.mooring.spar_wind_moment = [183034.454,157067.701,0.000,0.000] example.mooring.spar_current_force",
"= [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition =",
"example.mooring.water_depth = 218. example.mooring.mooring_type = 'CHAIN' example.mooring.anchor_type = 'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy",
"'PILE' example.mooring.fairlead_offset_from_shell = 0.5 example.mooring.shell_buoyancy = [0.000,257610.598,1356480.803,7074631.036] example.mooring.shell_mass = [55118.458,117635.366,193284.525,830352.783] example.mooring.bulkhead_mass = [0.000,19239.055,0.000,51299.008]",
"example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment = 3124462.452 example.mooring.RNA_wind_force = 820818.422 example.mooring.RNA_wind_moment",
"= 3. example.mooring.fixed_ballast_height = 5. example.mooring.permanent_ballast_density = 4492. example.mooring.fixed_ballast_density = 4000. example.mooring.water_depth =",
"19950.529 example.mooring.tower_wind_moment = 1634522.835 example.mooring.RNA_wind_force = 391966.178 example.mooring.RNA_wind_moment = 47028560.389 example.mooring.RNA_center_of_gravity_x = 4.1",
"sys_print(example.mooring) def example_218WD_10MW(): tt = time.time() example = optimizationMooring() example.mooring.fairlead_depth = 13. example.mooring.scope_ratio",
"[7.,8.,8.,13.] example.mooring.spar_wind_force = [2374.194,2345.237,0.000,0.000] example.mooring.spar_wind_moment = [137246.585,114777.740,0.000,0.0000] example.mooring.spar_current_force = [0.000,824040.566,1968613.701,182335.850] example.mooring.spar_current_moment = [0.000,37445057.967,67469109.912,353876.402]",
"= [1842.442,1861.334,0.000,0.000] example.mooring.spar_wind_moment = [100965.564,85586.296,0.000,0.000] example.mooring.spar_current_force = [0.000,449016.587,896445.823,49077.906] example.mooring.spar_current_moment = [0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness =",
"[0.000,19074749.640,28232958.052,72692.688] example.mooring.wall_thickness = [0.05,0.05,0.05,0.05] example.mooring.load_condition = 'N' # from,tower_RNA.py example.mooring.RNA_mass = 125000.000 example.mooring.tower_mass",
"= [13., 7., -5., -20.] example.mooring.spar_end_elevation = [7., -5., -20., -92.] example.mooring.spar_keel_to_CG =",
"example.mooring.tower_mass = 366952.000 example.mooring.tower_center_of_gravity = 33.381 example.mooring.RNA_keel_to_CG = 169.000 example.mooring.tower_wind_force = 33125.492 example.mooring.tower_wind_moment",
"openmdao.lib.drivers.api import COBYLAdriver, SLSQPdriver from mooring import Mooring import time import numpy as",
"= 4.1 example.run() print '--------------example_218WD_3MW------------------' print \"Elapsed time: \", time.time()-tt, \" seconds\" sys_print(example.mooring)"
] |
[
"PIL import ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def",
"Image from PIL import ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return",
"pytesseract import requests from PIL import Image from PIL import ImageFilter import io",
"import ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url):",
"from PIL import Image from PIL import ImageFilter import io def process_image(url): image=",
"import Image from PIL import ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN)",
"from PIL import ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image)",
"def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url): pattern_string = requests.get(url).content() return",
"import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url): pattern_string =",
"io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url): pattern_string = requests.get(url).content()",
"PIL import Image from PIL import ImageFilter import io def process_image(url): image= _get_image(url)",
"ImageFilter import io def process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url): pattern_string",
"import requests from PIL import Image from PIL import ImageFilter import io def",
"import pytesseract import requests from PIL import Image from PIL import ImageFilter import",
"process_image(url): image= _get_image(url) image.filter(ImageFilter.SHARPEN) return pytesseract.image_to_string(image) def _get_image(url): pattern_string = requests.get(url).content() return Image.open(io.StringIO(pattern_string))",
"requests from PIL import Image from PIL import ImageFilter import io def process_image(url):"
] |
[
"@VERSION : 1.0 *# #* @CREATION : 05 01, 2017 *# #* @MODIFICATION",
"handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url",
"client.app_utils import getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def",
"requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def isValid(text): return bool(re.search(r'\\blight\\b', text,",
"def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1'",
"import feedparser import requests import bs4 from client.app_utils import getTimezone from semantic.dates import",
"2017 *# #* <NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME>",
": 05 21, 2017 *# #* @AUTEURS : <NAME> *# #* @COPYRIGHT :",
"05 21, 2017 *# #* @AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright",
"querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned on the light, sir\" headers",
"from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile):",
"<NAME> *# #* <NAME> *# #* @LICENSE : MIT License (MIT) *# #******************************************************************************#",
"feedparser import requests import bs4 from client.app_utils import getTimezone from semantic.dates import DateService",
"down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned",
"if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned down the light,",
"= profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' + targetUrl + '/~/' +",
"getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic,",
"\"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence",
"@AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright (c) 2017 *# #* <NAME>",
"#******************************************************************************# import re import datetime import struct import urllib import feedparser import requests",
"= {\"op\":\"ALLtrue\"} sentence = \"I have turned on the light, sir\" headers =",
"@CREATION : 05 01, 2017 *# #* @MODIFICATION : 05 21, 2017 *#",
"targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' + targetUrl + '/~/'",
"2017 *# #* @AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright (c) 2017",
"else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned on the light, sir\"",
"'http://' + targetUrl + '/~/' + targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE):",
"bs4 from client.app_utils import getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\",",
"targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned down the",
"light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response",
"*# #* @CREATION : 05 01, 2017 *# #* @MODIFICATION : 05 21,",
"@COPYRIGHT : Copyright (c) 2017 *# #* <NAME> *# #* <NAME> *# #*",
"+ '/~/' + targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"}",
"targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' +",
"the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned on",
"*# #* @COPYRIGHT : Copyright (c) 2017 *# #* <NAME> *# #* <NAME>",
"21, 2017 *# #* @AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright (c)",
"2017 *# #* @MODIFICATION : 05 21, 2017 *# #* @AUTEURS : <NAME>",
"'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print",
"*# #* @AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright (c) 2017 *#",
"\"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text)",
"on the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\"",
"urllib import feedparser import requests import bs4 from client.app_utils import getTimezone from semantic.dates",
"<NAME> *# #* @LICENSE : MIT License (MIT) *# #******************************************************************************# import re import",
"*# #******************************************************************************# import re import datetime import struct import urllib import feedparser import",
"have turned down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I",
"(c) 2017 *# #* <NAME> *# #* <NAME> *# #* <NAME> *# #*",
"+ targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned down",
"*# #* <NAME> *# #* @LICENSE : MIT License (MIT) *# #******************************************************************************# import",
"'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence)",
"import re import datetime import struct import urllib import feedparser import requests import",
": 05 01, 2017 *# #* @MODIFICATION : 05 21, 2017 *# #*",
"turned down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have",
"[\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"]",
"sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response =",
"01, 2017 *# #* @MODIFICATION : 05 21, 2017 *# #* @AUTEURS :",
"= \"I have turned down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence",
"= { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url,",
"import datetime import struct import urllib import feedparser import requests import bs4 from",
"Light.py *# #* @VERSION : 1.0 *# #* @CREATION : 05 01, 2017",
"#* @VERSION : 1.0 *# #* @CREATION : 05 01, 2017 *# #*",
"(MIT) *# #******************************************************************************# import re import datetime import struct import urllib import feedparser",
"querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned down the light, sir\" else:",
"headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\",",
": Copyright (c) 2017 *# #* <NAME> *# #* <NAME> *# #* <NAME>",
"re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned down the light, sir\"",
"= [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn =",
"sentence = \"I have turned on the light, sir\" headers = { 'x-m2m-origin':",
"'/~/' + targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence",
"#* <NAME> *# #* <NAME> *# #* <NAME> *# #* @LICENSE : MIT",
"Copyright (c) 2017 *# #* <NAME> *# #* <NAME> *# #* <NAME> *#",
"import getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text,",
"#* <NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME> *# #*",
"*# #* @LICENSE : MIT License (MIT) *# #******************************************************************************# import re import datetime",
"targetAE = 'LED1' url = 'http://' + targetUrl + '/~/' + targetMn +",
"re import datetime import struct import urllib import feedparser import requests import bs4",
"@LICENSE : MIT License (MIT) *# #******************************************************************************# import re import datetime import struct",
"\"I have turned down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence =",
"#* <NAME> *# #* @LICENSE : MIT License (MIT) *# #******************************************************************************# import re",
"have turned on the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\",",
"<NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME>",
"import requests import bs4 from client.app_utils import getTimezone from semantic.dates import DateService WORDS",
": Light.py *# #* @VERSION : 1.0 *# #* @CREATION : 05 01,",
"datetime import struct import urllib import feedparser import requests import bs4 from client.app_utils",
"import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl =",
"struct import urllib import feedparser import requests import bs4 from client.app_utils import getTimezone",
"@TITRE : Light.py *# #* @VERSION : 1.0 *# #* @CREATION : 05",
"{\"op\":\"ALLfalse\"} sentence = \"I have turned down the light, sir\" else: querystring =",
"sentence = \"I have turned down the light, sir\" else: querystring = {\"op\":\"ALLtrue\"}",
": MIT License (MIT) *# #******************************************************************************# import re import datetime import struct import",
"+ targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence =",
"= 'http://' + targetUrl + '/~/' + targetMn + '/mn-name/' + targetAE if",
"\"I have turned on the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control':",
"{ 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers,",
"#* @CREATION : 05 01, 2017 *# #* @MODIFICATION : 05 21, 2017",
"= \"I have turned on the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\",",
": 1.0 *# #* @CREATION : 05 01, 2017 *# #* @MODIFICATION :",
"import struct import urllib import feedparser import requests import bs4 from client.app_utils import",
"\"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE =",
"05 01, 2017 *# #* @MODIFICATION : 05 21, 2017 *# #* @AUTEURS",
"#* @COPYRIGHT : Copyright (c) 2017 *# #* <NAME> *# #* <NAME> *#",
"= 'LED1' url = 'http://' + targetUrl + '/~/' + targetMn + '/mn-name/'",
"{\"op\":\"ALLtrue\"} sentence = \"I have turned on the light, sir\" headers = {",
"*# #* @VERSION : 1.0 *# #* @CREATION : 05 01, 2017 *#",
"requests import bs4 from client.app_utils import getTimezone from semantic.dates import DateService WORDS =",
"targetUrl + '/~/' + targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring =",
"import urllib import feedparser import requests import bs4 from client.app_utils import getTimezone from",
"response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def isValid(text): return",
"MIT License (MIT) *# #******************************************************************************# import re import datetime import struct import urllib",
"WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn",
"DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"]",
"<NAME> *# #* <NAME> *# #* <NAME> *# #* @LICENSE : MIT License",
"<NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME> *# #* @LICENSE",
"#* @LICENSE : MIT License (MIT) *# #******************************************************************************# import re import datetime import",
"semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl",
"*# #* <NAME> *# #* <NAME> *# #* <NAME> *# #* @LICENSE :",
"profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' + targetUrl +",
"*# #* <NAME> *# #* <NAME> *# #* @LICENSE : MIT License (MIT)",
"import bs4 from client.app_utils import getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\",",
"#******************************************************************************# #* @TITRE : Light.py *# #* @VERSION : 1.0 *# #* @CREATION",
"License (MIT) *# #******************************************************************************# import re import datetime import struct import urllib import",
"#* @TITRE : Light.py *# #* @VERSION : 1.0 *# #* @CREATION :",
"@MODIFICATION : 05 21, 2017 *# #* @AUTEURS : <NAME> *# #* @COPYRIGHT",
"#* <NAME> *# #* <NAME> *# #* @LICENSE : MIT License (MIT) *#",
"sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned on the light,",
"url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def isValid(text): return bool(re.search(r'\\blight\\b', text, re.IGNORECASE))",
"\"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def",
": <NAME> *# #* @COPYRIGHT : Copyright (c) 2017 *# #* <NAME> *#",
"turned on the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token':",
"+ targetUrl + '/~/' + targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring",
"*# #* @MODIFICATION : 05 21, 2017 *# #* @AUTEURS : <NAME> *#",
"'/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have turned",
"from client.app_utils import getTimezone from semantic.dates import DateService WORDS = [\"LIGHT\", \"DOWN\", \"ON\"]",
"} response = requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def isValid(text):",
"1.0 *# #* @CREATION : 05 01, 2017 *# #* @MODIFICATION : 05",
"#* @AUTEURS : <NAME> *# #* @COPYRIGHT : Copyright (c) 2017 *# #*",
"#* @MODIFICATION : 05 21, 2017 *# #* @AUTEURS : <NAME> *# #*",
"\"DOWN\", \"ON\"] def handle(text, mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE",
"= profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' + targetUrl",
"<NAME> *# #* @COPYRIGHT : Copyright (c) 2017 *# #* <NAME> *# #*",
"light, sir\" else: querystring = {\"op\":\"ALLtrue\"} sentence = \"I have turned on the",
"+ '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I have",
"= requests.request(\"POST\", url, headers=headers, params=querystring) print(response.text) print sentence mic.say(sentence) def isValid(text): return bool(re.search(r'\\blight\\b',",
"'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" } response = requests.request(\"POST\", url, headers=headers, params=querystring)",
"targetMn + '/mn-name/' + targetAE if re.search(r'\\bDOWN\\b',text,re.IGNORECASE): querystring = {\"op\":\"ALLfalse\"} sentence = \"I",
"'LED1' url = 'http://' + targetUrl + '/~/' + targetMn + '/mn-name/' +",
"mic, profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url =",
"the light, sir\" headers = { 'x-m2m-origin': \"admin:admin\", 'cache-control': \"no-cache\", 'postman-token': \"<PASSWORD>\" }",
"*# #* <NAME> *# #* <NAME> *# #* <NAME> *# #* <NAME> *#",
"profile): targetUrl = profile['target'][\"IP_PORT\"] targetMn = profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://'",
"url = 'http://' + targetUrl + '/~/' + targetMn + '/mn-name/' + targetAE",
"= {\"op\":\"ALLfalse\"} sentence = \"I have turned down the light, sir\" else: querystring",
"profile['target'][\"ID_MN\"] targetAE = 'LED1' url = 'http://' + targetUrl + '/~/' + targetMn"
] |
[] |
[] |
[
"), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value',",
"serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations",
"operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ],",
"[ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel(",
"serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={",
"from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'),",
"], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)),",
"import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations = [",
"migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)),",
"related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile',",
"-*- # Generated by Django 1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals",
"[ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True,",
"fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id',",
"models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract':",
"unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True,",
"('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',),",
"db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False,",
"] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')),",
"__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio',",
"-*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-16 15:20 from",
"('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False, 'get_latest_by':",
"coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-16 15:20 from __future__",
"= [ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc',",
"# Generated by Django 1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals from",
"by Django 1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals from django.db import",
"('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True,",
"models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"15:20 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class",
"1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals from django.db import migrations, models",
"= [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ),",
"models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False, 'get_latest_by': 'created',",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ]",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False, 'get_latest_by': 'created', }, ),",
"# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-16 15:20",
"on 2018-07-16 15:20 from __future__ import unicode_literals from django.db import migrations, models import",
"verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering':",
"('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False, 'get_latest_by': 'created', },",
"Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[",
"Django 1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals from django.db import migrations,",
"'0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False,",
"primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')), ],",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations =",
"name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[",
"name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio',",
"primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"2018-07-16 15:20 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion",
"migrations.CreateModel( name='Portfolio', fields=[ ('profile', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='portfolio', serialize=False, to='nc.Profile')), ], ), migrations.CreateModel( name='RawPortfolioData',",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata', to='nc.Portfolio')),",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rawdata',",
"related_name='rawdata', to='nc.Portfolio')), ], options={ 'ordering': ('-created',), 'abstract': False, 'get_latest_by': 'created', }, ), ]",
"utf-8 -*- # Generated by Django 1.11.13 on 2018-07-16 15:20 from __future__ import",
"<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-16",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel(",
"class Migration(migrations.Migration): dependencies = [ ('nc', '0034_auto_20180710_2209'), ] operations = [ migrations.CreateModel( name='Portfolio',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, db_index=True)), ('value', models.FloatField(default=-1.0)), ('portfolio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"Generated by Django 1.11.13 on 2018-07-16 15:20 from __future__ import unicode_literals from django.db"
] |
[
"\"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return",
"= OrderedDict() jdict['state'] = self.state if self.failure is not None: jdict['failure'] = self.failure",
"self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s,",
"iccid = None operator_code = None operator_name = None for line in lines:",
"model = jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod",
"SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims",
"rev) @classmethod def construct_from_mmcli(cls, lines): id = None imei = None mfr =",
"index): return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return pieces[-1] # ----------------------------------------------------------------------------------------------------------------",
"\"\"\" Constructor \"\"\" self.__state = state # string self.__failure = failure # string",
"match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims",
"operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi)",
"# string self.__operator_name = operator_name # string def __eq__(self, other): try: return self.imsi",
"= re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims):",
"= jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return cls(None,",
"re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if",
"for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems)",
"string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def",
"= re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line)",
"modem(self, index): return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return pieces[-1] #",
"= imsi # numeric string self.__iccid = iccid # numeric string self.__operator_code =",
"match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] == 'yes'",
": 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] :",
"@property def state(self): return self.__state @property def failure(self): return self.__failure @property def signal(self):",
"self.state if self.failure is not None: jdict['failure'] = self.failure jdict['signal'] = self.signal return",
"return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems",
"other.imei and self.mfr == other.mfr and \\ self.model == other.model and self.rev ==",
"reported_failure = match.groups()[0] failure = None if reported_failure == '--' else reported_failure continue",
"= match.groups()[0].strip() operator_name = None if reported_name == '--' else reported_name return cls(imsi,",
"Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\",",
"class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines):",
"recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality",
"line) if match: rev = match.groups()[0] continue return cls(id, imei, mfr, model, rev)",
"= None rev = None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line)",
"modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = []",
"other.rev except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id",
"if match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr",
"if not jdict: return None quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality,",
"67, \"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi :",
"def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] =",
"recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\"",
"# array of string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index):",
"class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10",
"construct_from_mmcli(cls, lines): imsi = None iccid = None operator_code = None operator_name =",
"numeric string self.__operator_code = operator_code # string self.__operator_name = operator_name # string def",
"EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if",
"class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent",
"== other.imei and self.mfr == other.mfr and \\ self.model == other.model and self.rev",
"@property def id(self): return self.__id @property def imei(self): return self.__imei @property def mfr(self):",
"JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module) --------------------------------",
"# int self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return",
"= None model = None rev = None for line in lines: match",
"in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) # ----------------------------------------------------------------------------------------------------------------",
"jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
"= match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue",
"continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name = None",
"Constructor \"\"\" self.__imsi = imsi # numeric string self.__iccid = iccid # numeric",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal)",
"% (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" #",
"cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims #",
"= re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line)",
"match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model =",
"self.__quality @property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict()",
"# string self.__mfr = mfr # string self.__model = model # string self.__rev",
"string self.__operator_code = operator_code # string self.__operator_name = operator_name # string def __eq__(self,",
"\"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path :",
"= match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue",
"# string self.__imei = imei # string self.__mfr = mfr # string self.__model",
"24 Mar 2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer :",
"= 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None",
"False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def iccid(self): return self.__iccid",
"@property def model(self): return self.__model @property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def",
"other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property",
"re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name = None if reported_name ==",
"other.model and self.rev == other.rev except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property",
"= re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line)",
"== '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality =",
"= self.failure jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code,",
"imsi = None iccid = None operator_code = None operator_name = None for",
"= iccid # numeric string self.__operator_code = operator_code # string self.__operator_name = operator_name",
"signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67",
"= jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls,",
"if not jdict: return None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code =",
"# -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model",
"# -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"@property def failure(self): return self.__failure @property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def",
"__len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self, index):",
"return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei']",
"self.__operator_code = operator_code # string self.__operator_name = operator_name # string def __eq__(self, other):",
"def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self,",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None quality =",
"jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name']",
"def id(self): return self.__id @property def imei(self): return self.__imei @property def mfr(self): return",
"match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module)",
"from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\"",
"line) if match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match:",
"[] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return",
"jdict = OrderedDict() jdict['state'] = self.state if self.failure is not None: jdict['failure'] =",
"pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\"",
"from collections import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import JSONable #",
"jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\"",
"match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)',",
"== other.id and self.imei == other.imei and self.mfr == other.mfr and \\ self.model",
"jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None)",
"recent = None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match:",
"reported_name = match.groups()[0].strip() operator_name = None if reported_name == '--' else reported_name return",
"None operator_code = None operator_name = None for line in lines: match =",
"= operator_code # string self.__operator_name = operator_name # string def __eq__(self, other): try:",
"continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] == 'yes' continue",
"def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) #",
"if match: reported_failure = match.groups()[0] failure = None if reported_failure == '--' else",
"= match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls):",
"None: jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev =",
"\"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value",
"recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def recent(self):",
"self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] =",
"# numeric string self.__operator_code = operator_code # string self.__operator_name = operator_name # string",
"re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\"",
"sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example",
"return self.__quality @property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict =",
": /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name :",
"match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return",
"match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue match",
"string self.__failure = failure # string self.__signal = signal # Signal # ----------------------------------------------------------------------------------------------------------------",
"operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi",
"jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod",
": 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision",
"failure = None if reported_failure == '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)',",
"None id = jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model')",
"lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue match =",
"class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL",
"id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0]",
"/org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = [] for line",
"match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] == 'yes' continue return",
"self.__failure @property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict()",
"classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None",
"def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] =",
"def modem(self, index): return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return pieces[-1]",
"line) if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor",
"index): pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"# ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def failure(self): return self.__failure @property",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int",
"connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE =",
"if match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure",
"= self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def",
"-------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls,",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\",
"return cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr,",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None imsi = jdict.get('imsi')",
"match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue match",
"__eq__(self, other): try: return self.imsi == other.imsi and self.iccid == other.iccid and \\",
"QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON:",
"line) if match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match:",
"len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self, index): pieces =",
": 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return",
"operator_name # string def __eq__(self, other): try: return self.imsi == other.imsi and self.iccid",
"if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\"",
"model, rev): \"\"\" Constructor \"\"\" self.__id = id # string self.__imei = imei",
"and \\ self.operator_code == other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError): return",
"# ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid)",
": -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" #",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" % \\",
"return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] = self.state if",
"8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999",
"jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev']",
"mfr = jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr,",
"Constructor \"\"\" self.__id = id # string self.__imei = imei # string self.__mfr",
"and self.mfr == other.mfr and \\ self.model == other.model and self.rev == other.rev",
"if not jdict: return None state = jdict.get('state') failure = jdict.get('failure') signal =",
": yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if",
"match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name = None if",
"index): pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"self.__id = id # string self.__imei = imei # string self.__mfr = mfr",
"self.id == other.id and self.imei == other.imei and self.mfr == other.mfr and \\",
"yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not",
"def imsi(self): return self.__imsi @property def iccid(self): return self.__iccid @property def operator_code(self): return",
"def construct_from_mmcli(cls, lines): sims = [] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)',",
"if match: reported_name = match.groups()[0].strip() operator_name = None if reported_name == '--' else",
"@classmethod def construct_from_mmcli(cls, lines): modems = [] for line in lines: match =",
"recent = match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod def",
"def imei(self): return self.__imei @property def mfr(self): return self.__mfr @property def model(self): return",
"rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\"",
"= self.state if self.failure is not None: jdict['failure'] = self.failure jdict['signal'] = self.signal",
"= recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def",
"__str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object):",
"sims # array of string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self,",
"operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi",
"collections import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import JSONable # --------------------------------------------------------------------------------------------------------------------",
"= re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line)",
"jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model']",
"= self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s,",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = [] for line in lines: match",
"# -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict):",
"imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0]",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id",
"# array of string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index):",
"\"\"\" self.__state = state # string self.__failure = failure # string self.__signal =",
"rev = None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match:",
"return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s,",
"recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state,",
"\"\"\" import re from collections import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json",
"= self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" %",
"lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue match =",
"= modems # array of string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def",
"and self.imei == other.imei and self.mfr == other.mfr and \\ self.model == other.model",
"Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value",
"== '--' else reported_name return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict # ----------------------------------------------------------------------------------------------------------------",
"model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0]",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims # array of",
"= jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi =",
"imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id = id # string self.__imei",
"model(self): return self.__model @property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict",
"Mar 2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM",
"line) if match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match:",
"= re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] == 'yes' continue return cls(state,",
"@property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality']",
"construct_from_jdict(cls, jdict): if not jdict: return None state = jdict.get('state') failure = jdict.get('failure')",
"self.__iccid @property def operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name # ----------------------------------------------------------------------------------------------------------------",
"quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent = recent",
"jdict['state'] = self.state if self.failure is not None: jdict['failure'] = self.failure jdict['signal'] =",
"for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims)",
"cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\"",
"def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state = state # string",
"match: reported_name = match.groups()[0].strip() operator_name = None if reported_name == '--' else reported_name",
"self.__imsi = imsi # numeric string self.__iccid = iccid # numeric string self.__operator_code",
": QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\"",
"imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return",
"AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def imei(self):",
"modems): \"\"\" Constructor \"\"\" self.__modems = modems # array of string def __len__(self):",
"string self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state",
"# ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] = self.state if self.failure is",
"match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)',",
"modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict):",
"jdict): if not jdict: return None quality = jdict.get('quality') recent = jdict.get('recent') return",
"None recent = None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if",
"construct_from_jdict(cls, jdict): if not jdict: return None quality = jdict.get('quality') recent = jdict.get('recent')",
"= jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name)",
"continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue match =",
"Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile",
"recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent = recent #",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" % \\ (self.imsi,",
"\"\"\" self.__modems = modems # array of string def __len__(self): return len(self.__modems) #",
"= Datum.int(quality) # int self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def",
"def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] =",
"continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue match =",
"cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model,",
"construct_from_jdict(cls, jdict): if not jdict: return None id = jdict.get('id') imei = jdict.get('imei')",
"*args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" % \\ (self.imsi, self.iccid, self.operator_code, self.operator_name)",
"self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\"",
"def __eq__(self, other): try: return self.id == other.id and self.imei == other.imei and",
"def failure(self): return self.__failure @property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self):",
"for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0]",
"None quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls):",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable):",
"match: rev = match.groups()[0] continue return cls(id, imei, mfr, model, rev) # ----------------------------------------------------------------------------------------------------------------",
"null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\"",
"imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi # numeric string",
"return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def",
"quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return",
"match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"iccid # numeric string self.__operator_code = operator_code # string self.__operator_name = operator_name #",
"match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei =",
": 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"}",
"\"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent = recent # bool",
"sim(self, index): return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return pieces[-1] #",
"/org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = [] for line",
"__init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state = state # string self.__failure",
"Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : --",
"return cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable):",
": /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = [] for",
"ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent :",
"= re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line)",
"def iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code @property def operator_name(self): return",
"== other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError): return False # ----------------------------------------------------------------------------------------------------------------",
"= \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None",
"None iccid = None operator_code = None operator_name = None for line in",
"@property def operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def",
"\"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection ---------------",
"\"operator-name\": \"<NAME>\"} \"\"\" import re from collections import OrderedDict from scs_core.data.datum import Datum",
"modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"# string self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return",
"def state(self): return self.__state @property def failure(self): return self.__failure @property def signal(self): return",
"iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name",
"as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr",
"OrderedDict() jdict['state'] = self.state if self.failure is not None: jdict['failure'] = self.failure jdict['signal']",
"return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ----------------------------------------------------------------------------------------------------------------",
"modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G",
"@property def iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code @property def operator_name(self):",
"not jdict: return None state = jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal'))",
"INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei :",
"# ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def iccid(self): return self.__iccid @property",
"rev): \"\"\" Constructor \"\"\" self.__id = id # string self.__imei = imei #",
"= self.model jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"@classmethod def construct_from_jdict(cls, jdict): if not jdict: return None state = jdict.get('state') failure",
"failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def",
"None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name')",
"match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name =",
"012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections import OrderedDict from scs_core.data.datum import",
"return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim :",
"10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None quality",
"self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return jdict #",
"---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return",
"failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value :",
"= re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line)",
"self.model == other.model and self.rev == other.rev except (TypeError, AttributeError): return False #",
"(self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected",
"imei(self): return self.__imei @property def mfr(self): return self.__mfr @property def model(self): return self.__model",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # --------------------------------------------------------------------------------------------------------------------",
"return self.__iccid @property def operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name #",
"= OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] =",
"\"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections import OrderedDict",
"Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"-------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls,",
"self.__state @property def failure(self): return self.__failure @property def signal(self): return self.__signal # ----------------------------------------------------------------------------------------------------------------",
"model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev): \"\"\" Constructor",
"Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ----------------------------------------------------------------------------------------------------------------",
"reported_name return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code,",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class",
"# string self.__failure = failure # string self.__signal = signal # Signal #",
"modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"numeric string self.__iccid = iccid # numeric string self.__operator_code = operator_code # string",
"self.operator_code == other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError): return False #",
"Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state =",
"# Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def failure(self): return",
"{\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi",
"def number(self, index): pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi =",
"# string def __eq__(self, other): try: return self.id == other.id and self.imei ==",
"Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state = None failure",
"\"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None id",
"% self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"# string self.__model = model # string self.__rev = rev # string def",
"match: reported_failure = match.groups()[0] failure = None if reported_failure == '--' else reported_failure",
"OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object):",
"if not jdict: return None id = jdict.get('id') imei = jdict.get('imei') mfr =",
"-- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ----------------------------------------------------------------------------------------------------------------",
"rev # string def __eq__(self, other): try: return self.id == other.id and self.imei",
"*args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\"",
"giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\":",
"= match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue",
"2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED",
"return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self, index): pieces",
"__eq__(self, other): try: return self.id == other.id and self.imei == other.imei and self.mfr",
"re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if",
"(<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL",
"Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\":",
"def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor",
"bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def recent(self): return self.__recent",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state = state #",
"match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems",
"jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr, model, rev)",
"in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue match",
"self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"= operator_name # string def __eq__(self, other): try: return self.imsi == other.imsi and",
"self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s,",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None state = jdict.get('state')",
"= self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] =",
"self.__sims = sims # array of string def __len__(self): return len(self.__sims) # ----------------------------------------------------------------------------------------------------------------",
"failure(self): return self.__failure @property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id =",
"Constructor \"\"\" self.__state = state # string self.__failure = failure # string self.__signal",
"234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2",
"other.iccid and \\ self.operator_code == other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError):",
"= self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s,",
"if match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent",
"self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : --",
"return self.__mfr @property def model(self): return self.__model @property def rev(self): return self.__rev #",
"jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state,",
"__SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return",
"if self.failure is not None: jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict",
"None if reported_name == '--' else reported_name return cls(imsi, iccid, operator_code, operator_name) #",
"\"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection",
"except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property",
"-- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\":",
"lines): state = None failure = None quality = None recent = None",
"---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable):",
"jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None",
"# string def __eq__(self, other): try: return self.imsi == other.imsi and self.iccid ==",
"self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems",
"None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id =",
"@classmethod def construct_from_mmcli(cls, lines): id = None imei = None mfr = None",
"@classmethod def construct_from_jdict(cls, jdict): if not jdict: return None id = jdict.get('id') imei",
"match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure =",
"def construct_from_jdict(cls, jdict): if not jdict: return None imsi = jdict.get('imsi') iccid =",
"= None imei = None mfr = None model = None rev =",
"= None operator_code = None operator_name = None for line in lines: match",
"yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not",
"jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
"self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"(self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ----------------------------------------------------------------------------------------------------------------",
"lines): imsi = None iccid = None operator_code = None operator_name = None",
"sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2]",
"iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0]",
"= match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue",
"= imei # string self.__mfr = mfr # string self.__model = model #",
"cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state = None failure = None",
"Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent = recent # bool #",
"self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property",
"\"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state :",
"jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return",
"Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\":",
"= self.quality jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"sims): \"\"\" Constructor \"\"\" self.__sims = sims # array of string def __len__(self):",
"imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev):",
"def quality(self): return self.__quality @property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self):",
"operator_name = None if reported_name == '--' else reported_name return cls(imsi, iccid, operator_code,",
"Datum.int(quality) # int self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self):",
"= [] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0])",
"match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue match",
"# -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value :",
"for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0]",
"mfr, model, rev): \"\"\" Constructor \"\"\" self.__id = id # string self.__imei =",
"---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return",
"jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state",
"UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return",
"match.groups()[0] failure = None if reported_failure == '--' else reported_failure continue match =",
"try: return self.imsi == other.imsi and self.iccid == other.iccid and \\ self.operator_code ==",
": 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length :",
"return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor",
"= jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines):",
"jdict): if not jdict: return None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code",
"mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0]",
"other.operator_name except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi",
"match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure =",
"state = None failure = None quality = None recent = None for",
"self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] =",
"failure, signal) @classmethod def construct_from_mmcli(cls, lines): state = None failure = None quality",
"None model = None rev = None for line in lines: match =",
"\"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"}",
"in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) # ----------------------------------------------------------------------------------------------------------------",
"= None mfr = None model = None rev = None for line",
"match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)',",
"False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def imei(self): return self.__imei",
"self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims",
"string self.__imei = imei # string self.__mfr = mfr # string self.__model =",
"\"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None imsi",
"def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id,",
"failure, signal): \"\"\" Constructor \"\"\" self.__state = state # string self.__failure = failure",
"def __eq__(self, other): try: return self.imsi == other.imsi and self.iccid == other.iccid and",
"of string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index]",
"return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self, index): pieces",
"modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = []",
"= jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev =",
"= re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line)",
"match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure = None if",
"and self.iccid == other.iccid and \\ self.operator_code == other.operator_code and self.operator_name == other.operator_name",
"Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state",
"mfr(self): return self.__mfr @property def model(self): return self.__model @property def rev(self): return self.__rev",
"\"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict:",
"match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)',",
"return self.__operator_code @property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict =",
"self.__failure = failure # string self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property",
"self.failure is not None: jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict #",
"Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code :",
"= self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\"",
"= id # string self.__imei = imei # string self.__mfr = mfr #",
"rev = match.groups()[0] continue return cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def",
"\"\"\" self.__sims = sims # array of string def __len__(self): return len(self.__sims) #",
"== 'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE,",
"line) if match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match:",
"jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict # ----------------------------------------------------------------------------------------------------------------",
"JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\",",
"continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue match =",
"(TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def",
"imei # string self.__mfr = mfr # string self.__model = model # string",
"return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid']",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None id =",
"jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return cls(id, imei,",
"= self.operator_code jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue match",
"line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue",
"= None recent = None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line)",
"= re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure = None if reported_failure",
"self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] = self.state if self.failure",
"match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)',",
"None quality = None recent = None for line in lines: match =",
"**kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim",
"def construct_from_jdict(cls, jdict): if not jdict: return None id = jdict.get('id') imei =",
"---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def iccid(self): return self.__iccid @property def",
"return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None iccid",
"def as_json(self): jdict = OrderedDict() jdict['state'] = self.state if self.failure is not None:",
"match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue match",
"on 24 Mar 2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer",
"class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines):",
": EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict):",
": 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789",
"= self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s,",
"@author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model",
"@property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id']",
"= failure # string self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def",
"as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code",
"00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\"",
"= jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod def",
"match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)',",
"\"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband",
"other): try: return self.imsi == other.imsi and self.iccid == other.iccid and \\ self.operator_code",
"---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/') return",
"= OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] =",
"\\ (self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state :",
"def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict",
"if match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei",
"return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev)",
"self.iccid == other.iccid and \\ self.operator_code == other.operator_code and self.operator_name == other.operator_name except",
"sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\":",
"{\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path",
"== other.iccid and \\ self.operator_code == other.operator_code and self.operator_name == other.operator_name except (TypeError,",
"\"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason :",
"\"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims =",
"operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None iccid = None operator_code =",
"imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0]",
"= match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] ==",
"# -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls,",
"modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM",
"def construct_from_mmcli(cls, lines): state = None failure = None quality = None recent",
"sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\":",
"modems # array of string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self,",
"__init__(self, id, imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id = id #",
"# numeric string self.__iccid = iccid # numeric string self.__operator_code = operator_code #",
"true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid",
"return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\"",
"def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent",
"= re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line)",
"modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151",
"@property def mfr(self): return self.__mfr @property def model(self): return self.__model @property def rev(self):",
"if match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model",
"# ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent",
"jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent)",
"return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def",
"from scs_core.data.datum import Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\"",
"self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes",
"self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) #",
"= model # string self.__rev = rev # string def __eq__(self, other): try:",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure,",
"continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure = None",
"\"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections import",
"= None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi",
"def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims # array of string",
"@classmethod def construct_from_jdict(cls, jdict): if not jdict: return None imsi = jdict.get('imsi') iccid",
"line) if match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match:",
"operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict",
"str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict #",
"reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue match",
"reported_name == '--' else reported_name return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def",
"id, imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id = id # string",
"string self.__iccid = iccid # numeric string self.__operator_code = operator_code # string self.__operator_name",
"= None iccid = None operator_code = None operator_name = None for line",
"\"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband",
"@property def imei(self): return self.__imei @property def mfr(self): return self.__mfr @property def model(self):",
"re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if",
": 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL",
"---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def recent(self): return self.__recent # ----------------------------------------------------------------------------------------------------------------",
"jdict: return None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name",
"def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self,",
"999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\",",
"\"\"\" self.__imsi = imsi # numeric string self.__iccid = iccid # numeric string",
"867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems # array of",
"rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] = self.id",
"modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\",",
": -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\":",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = [] for line in lines:",
"---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code']",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems # array",
"\"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections import OrderedDict from scs_core.data.datum",
"signal): \"\"\" Constructor \"\"\" self.__state = state # string self.__failure = failure #",
"\"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems =",
"lines): id = None imei = None mfr = None model = None",
"__init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims # array of string def",
"return None state = jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state,",
"def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi #",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) #",
"string self.__rev = rev # string def __eq__(self, other): try: return self.id ==",
"jdict: return None state = jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return",
"cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality,",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = [] for line in lines: match",
"self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value",
"\"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes",
"Constructor \"\"\" self.__sims = sims # array of string def __len__(self): return len(self.__sims)",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None quality = jdict.get('quality')",
"jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return jdict # ----------------------------------------------------------------------------------------------------------------",
"= match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue",
"None state = jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure,",
"operator_code # string self.__operator_name = operator_name # string def __eq__(self, other): try: return",
"None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality)",
"self.quality jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"\"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = [] for line in",
"string self.__mfr = mfr # string self.__model = model # string self.__rev =",
"model # string self.__rev = rev # string def __eq__(self, other): try: return",
"EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM",
"def __init__(self, id, imei, mfr, model, rev): \"\"\" Constructor \"\"\" self.__id = id",
"lines): sims = [] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if",
"-------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE =",
"number(self, index): pieces = self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not",
"**kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b",
"jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def",
"---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def imei(self): return self.__imei @property def",
"jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id =",
"re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0] == 'yes' continue return cls(state, failure,",
"Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 #",
"quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent = match.groups()[0]",
"None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state =",
"return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name):",
"imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id = None imei =",
"\"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict:",
": /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = [] for",
"other.id and self.imei == other.imei and self.mfr == other.mfr and \\ self.model ==",
"= match.groups()[0] failure = None if reported_failure == '--' else reported_failure continue match",
"[] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return",
"= match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid = match.groups()[0] continue",
"string self.__operator_name = operator_name # string def __eq__(self, other): try: return self.imsi ==",
": yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if",
"self.__imei @property def mfr(self): return self.__mfr @property def model(self): return self.__model @property def",
"Constructor \"\"\" self.__modems = modems # array of string def __len__(self): return len(self.__modems)",
"line) if match: reported_failure = match.groups()[0] failure = None if reported_failure == '--'",
"def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi'] =",
"cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id = None imei",
"self.operator_code jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"= None if reported_failure == '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line)",
"self.__model = model # string self.__rev = rev # string def __eq__(self, other):",
"lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue match =",
"self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls,",
"number(self, index): pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):",
"string def __eq__(self, other): try: return self.imsi == other.imsi and self.iccid == other.iccid",
"other.imsi and self.iccid == other.iccid and \\ self.operator_code == other.operator_code and self.operator_name ==",
"self.__imsi @property def iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code @property def",
"mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev): \"\"\"",
"state = jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal)",
"jdict): if not jdict: return None id = jdict.get('id') imei = jdict.get('imei') mfr",
"sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name",
"= re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue return cls(id, imei, mfr,",
"== other.model and self.rev == other.rev except (TypeError, AttributeError): return False # ----------------------------------------------------------------------------------------------------------------",
"re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure = None if reported_failure ==",
"= match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name",
"modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\":",
"if match: rev = match.groups()[0] continue return cls(id, imei, mfr, model, rev) #",
"= re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line)",
"# ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self, index): pieces = self.modem(index).split('/')",
"construct_from_mmcli(cls, lines): id = None imei = None mfr = None model =",
"return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state = None failure =",
"match: recent = match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod",
"match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)',",
"return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\"",
"lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def",
"**kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" #",
"def model(self): return self.__model @property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self):",
"= None if reported_name == '--' else reported_name return cls(imsi, iccid, operator_code, operator_name)",
"== other.mfr and \\ self.model == other.model and self.rev == other.rev except (TypeError,",
"(self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent :",
"continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue match =",
"\"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0",
"Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"return None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name =",
"modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module",
"construct_from_mmcli(cls, lines): modems = [] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line)",
"pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # --------------------------------------------------------------------------------------------------------------------",
"\"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67",
"= None failure = None quality = None recent = None for line",
"\"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections",
"id(self): return self.__id @property def imei(self): return self.__imei @property def mfr(self): return self.__mfr",
"= state # string self.__failure = failure # string self.__signal = signal #",
": giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON:",
"return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems #",
"-------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if",
"{\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from",
"imei = None mfr = None model = None rev = None for",
"line) if match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match:",
"match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name =",
"@classmethod def construct_from_mmcli(cls, lines): sims = [] for line in lines: match =",
"# bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def recent(self): return",
"not jdict: return None imsi = jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code')",
"= rev # string def __eq__(self, other): try: return self.id == other.id and",
": QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example",
"{\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\":",
"\\ self.model == other.model and self.rev == other.rev except (TypeError, AttributeError): return False",
"as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict #",
"ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent :",
": 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] :",
"# ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/')",
"mfr = None model = None rev = None for line in lines:",
"= None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id",
"/org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff",
"modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict:",
"\"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re from collections import OrderedDict from",
"self.__id @property def imei(self): return self.__imei @property def mfr(self): return self.__mfr @property def",
"cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\"",
"jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def",
"operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\"",
"return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality",
"= self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] = self.rev return jdict",
"signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state =",
"sims = [] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line) if match:",
"operator_name = None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match:",
"return None id = jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model =",
"-------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model :",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" %",
": connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE",
"modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\"",
"'--' else reported_name return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi,",
"modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls,",
"modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example",
"\"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason",
"return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer",
"iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor",
"def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" % \\ (self.imsi, self.iccid,",
"def sim(self, index): return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return pieces[-1]",
"in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue match",
"= self.sim(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" %",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None state =",
"= match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0] failure",
"jdict: return None id = jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model",
"quality = None recent = None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)',",
"line) if match: reported_name = match.groups()[0].strip() operator_name = None if reported_name == '--'",
"\"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): sims = [] for line in",
"__init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi # numeric",
"@property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['imsi']",
"id = jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev",
"sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1]",
"None if reported_failure == '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if",
"**kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable):",
"sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length",
"def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems # array of string",
"return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims #",
"@property def quality(self): return self.__quality @property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def",
"line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue",
"iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi # numeric string self.__iccid",
"self.imsi == other.imsi and self.iccid == other.iccid and \\ self.operator_code == other.operator_code and",
"def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\"",
"failure = None quality = None recent = None for line in lines:",
"def number(self, index): pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
"return self.imsi == other.imsi and self.iccid == other.iccid and \\ self.operator_code == other.operator_code",
"= OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def",
"operator_code = None operator_name = None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)',",
"Created on 24 Mar 2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b",
"2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\": \"456\",",
"def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\"",
"def construct_from_mmcli(cls, lines): modems = [] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)',",
"\"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\" modem.generic.sim : /org/freedesktop/ModemManager1/SIM/0",
"modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\",",
"line) if match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match:",
"and self.operator_name == other.operator_name except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def",
"\"\"\" self.__id = id # string self.__imei = imei # string self.__mfr =",
"67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls,",
"Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile",
"self.__model @property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict()",
"operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None iccid = None operator_code",
"except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property",
"re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if",
"return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) #",
"if reported_name == '--' else reported_name return cls(imsi, iccid, operator_code, operator_name) # ----------------------------------------------------------------------------------------------------------------",
"yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber Identity",
"id = None imei = None mfr = None model = None rev",
"return self.__failure @property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict =",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims # array",
"\"\"\" Created on 24 Mar 2021 @author: <NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier :",
"state # string self.__failure = failure # string self.__signal = signal # Signal",
"continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code = match.groups()[0] continue match =",
"OrderedDict() jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name",
"= jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return cls(id,",
"jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls,",
": 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"\"mfr\": \"QUALCOMM INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state",
"= None quality = None recent = None for line in lines: match",
"reported_failure == '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality",
"return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality,",
"__str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class SIM(JSONable): \"\"\" classdocs",
"QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei",
"imsi # numeric string self.__iccid = iccid # numeric string self.__operator_code = operator_code",
"@property def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state']",
"== other.imsi and self.iccid == other.iccid and \\ self.operator_code == other.operator_code and self.operator_name",
"\"\"\" Constructor \"\"\" self.__modems = modems # array of string def __len__(self): return",
"self.rev == other.rev except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self):",
"match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue return",
"\"recent\": true}} SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667",
": 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\", \"iccid\":",
": 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\":",
"67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}}",
"pieces = self.modem(index).split('/') return pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\"",
"def construct_from_jdict(cls, jdict): if not jdict: return None state = jdict.get('state') failure =",
"mfr # string self.__model = model # string self.__rev = rev # string",
"return self.__state @property def failure(self): return self.__failure @property def signal(self): return self.__signal #",
"= None operator_name = None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line)",
"__init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems # array of string def",
"self.__rev = rev # string def __eq__(self, other): try: return self.id == other.id",
"3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision :",
"\"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent",
"# -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE",
"id # string self.__imei = imei # string self.__mfr = mfr # string",
"match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid =",
"self.failure jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"\"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer :",
"@property def imsi(self): return self.__imsi @property def iccid(self): return self.__iccid @property def operator_code(self):",
"\"\"\" Constructor \"\"\" self.__id = id # string self.__imei = imei # string",
"jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
"signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def failure(self):",
"str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"-------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67",
"return self.__imsi @property def iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code @property",
"line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue",
"OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model",
"re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0] continue match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if",
"if match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if match: iccid",
"\"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ----------------------------------------------------------------------------------------------------------------",
"# ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei",
"---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid, operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi",
"modems = [] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match:",
"try: return self.id == other.id and self.imei == other.imei and self.mfr == other.mfr",
"self.id jdict['imei'] = self.imei jdict['mfr'] = self.mfr jdict['model'] = self.model jdict['rev'] = self.rev",
"construct_from_mmcli(cls, lines): state = None failure = None quality = None recent =",
"'yes' continue return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None,",
"__str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # --------------------------------------------------------------------------------------------------------------------",
"None rev = None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if",
"return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['quality'] = self.quality jdict['recent']",
"re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi = match.groups()[0] continue match = re.match(r'sim\\.properties\\.iccid\\s+:\\s+([\\d]+)', line) if",
"# ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def imei(self): return self.__imei @property",
"match = re.match(r'.*\\.imei\\s+:\\s+(\\d+)', line) if match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)',",
"other.mfr and \\ self.model == other.model and self.rev == other.rev except (TypeError, AttributeError):",
"cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ----------------------------------------------------------------------------------------------------------------",
"not jdict: return None quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent)",
"@classmethod def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\"",
"rev = jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines):",
"continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue return cls(id,",
"mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class",
"= jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None) # ----------------------------------------------------------------------------------------------------------------",
"self.__imei = imei # string self.__mfr = mfr # string self.__model = model",
"re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if",
"imsi(self): return self.__imsi @property def iccid(self): return self.__iccid @property def operator_code(self): return self.__operator_code",
"= Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls, lines): state = None",
"None mfr = None model = None rev = None for line in",
"None failure = None quality = None recent = None for line in",
"= str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict",
"string self.__model = model # string self.__rev = rev # string def __eq__(self,",
"index): return self.__sims[index] def number(self, index): pieces = self.sim(index).split('/') return pieces[-1] # ----------------------------------------------------------------------------------------------------------------",
"def signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] =",
"\"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None state",
"Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code",
"import Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] :",
"ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems",
"= re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems):",
"= jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return cls(id, imei, mfr, model,",
"== other.rev except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return",
"def as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr'] =",
"% (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class Signal(JSONable): \"\"\" modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent",
"@classmethod def construct_from_mmcli(cls, lines): state = None failure = None quality = None",
"jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s,",
"def construct_from_mmcli(cls, lines): imsi = None iccid = None operator_code = None operator_name",
"imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev) # --------------------------------------------------------------------------------------------------------------------",
"state(self): return self.__state @property def failure(self): return self.__failure @property def signal(self): return self.__signal",
"self.__mfr = mfr # string self.__model = model # string self.__rev = rev",
"self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason",
"---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] = self.imei jdict['mfr']",
"state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match: reported_failure = match.groups()[0]",
"---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def failure(self): return self.__failure @property def",
"@classmethod def construct_from_jdict(cls, jdict): if not jdict: return None quality = jdict.get('quality') recent",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) #",
"__str__(self, *args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei,",
"= [] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0])",
"def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class",
"----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband",
"return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def iccid(self): return",
"= str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def",
"match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)',",
"re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\"",
"867962041294151 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None",
"string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def",
"cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality =",
"self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state : connected modem.generic.state-failed-reason :",
"def construct_from_jdict(cls, jdict): if not jdict: return None quality = jdict.get('quality') recent =",
"= match.groups()[0] continue return cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self,",
"else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0] continue",
"operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi # numeric string self.__iccid = iccid",
"line) if match: recent = match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality,",
"modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems =",
"re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue return cls(id, imei, mfr, model,",
"def mfr(self): return self.__mfr @property def model(self): return self.__model @property def rev(self): return",
"if match: operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name",
"--------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes",
"INCORPORATED\", \"model\": \"QUECTEL Mobile Broadband Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected",
"model, rev) @classmethod def construct_from_mmcli(cls, lines): id = None imei = None mfr",
"jdict['model'] = self.model jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,",
": EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\":",
"return self.__model @property def rev(self): return self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict =",
"jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Modem:{id:%s,",
"\"<NAME>\"} \"\"\" import re from collections import OrderedDict from scs_core.data.datum import Datum from",
"---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None id = jdict.get('id')",
"recent) @classmethod def null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent):",
"# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # -------------------------------------------------------------------------------------------------------------------- class",
"None operator_name = None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if",
"Module\", \"rev\": \"EC21EFAR06A01M4G\"} ModemConnection --------------- modem.generic.state : connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value :",
"% \\ (self.id, self.imei, self.mfr, self.model, self.rev) # -------------------------------------------------------------------------------------------------------------------- class ModemConnection(JSONable): \"\"\" modem.generic.state",
"re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if",
"jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev')",
"line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) #",
"return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims = sims",
"\"\"\" self.__quality = Datum.int(quality) # int self.__recent = recent # bool # ----------------------------------------------------------------------------------------------------------------",
"self.__iccid = iccid # numeric string self.__operator_code = operator_code # string self.__operator_name =",
"return self.id == other.id and self.imei == other.imei and self.mfr == other.mfr and",
"self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" %",
"modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67,",
"None for line in lines: match = re.match(r'sim\\.properties\\.imsi\\s+:\\s+([\\d]+)', line) if match: imsi =",
"\"\"\" Constructor \"\"\" self.__imsi = imsi # numeric string self.__iccid = iccid #",
"re from collections import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import JSONable",
"self.__rev # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['id'] = self.id jdict['imei'] =",
"pieces[-1] # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIMList:{sims:%s}\" % self.__sims # --------------------------------------------------------------------------------------------------------------------",
"iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None iccid = None",
"else reported_name return cls(imsi, iccid, operator_code, operator_name) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, imsi, iccid,",
": yes example JSON: {\"state\": \"connected\", \"signal\": {\"quality\": 67, \"recent\": true}} SIM (Subscriber",
"-------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054 sim.properties.operator-code : 23410",
"lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def",
"signal) @classmethod def construct_from_mmcli(cls, lines): state = None failure = None quality =",
"self.__quality = Datum.int(quality) # int self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property",
"mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id = None imei = None",
"23410 sim.properties.operator-name : giffgaff sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112",
"model = None rev = None for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)',",
"class SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not",
"return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def imei(self): return",
"<NAME> (<EMAIL>) Modem ----- modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED modem.generic.model :",
": 67 modem.generic.signal-quality.recent : yes \"\"\" __SIGNIFICANT_QUALITY_DIFFERENCE = 10 # ---------------------------------------------------------------------------------------------------------------- @classmethod def",
"as_json(self): jdict = OrderedDict() jdict['state'] = self.state if self.failure is not None: jdict['failure']",
"= mfr # string self.__model = model # string self.__rev = rev #",
"# string self.__rev = rev # string def __eq__(self, other): try: return self.id",
"jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s,",
"operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_mmcli(cls, lines): modems = [] for line in lines:",
"__init__(self, quality, recent): \"\"\" Constructor \"\"\" self.__quality = Datum.int(quality) # int self.__recent =",
"other): try: return self.id == other.id and self.imei == other.imei and self.mfr ==",
"cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor \"\"\" self.__modems = modems #",
"array of string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return",
"construct_from_mmcli(cls, lines): sims = [] for line in lines: match = re.match(r'modem\\.generic\\.sim\\s+:\\s+([\\S]+)', line)",
"= jdict.get('state') failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod",
"= signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def",
"return self.__imei @property def mfr(self): return self.__mfr @property def model(self): return self.__model @property",
"def operator_code(self): return self.__operator_code @property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self):",
": connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON:",
"not jdict: return None id = jdict.get('id') imei = jdict.get('imei') mfr = jdict.get('mfr')",
"and self.rev == other.rev except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def",
"if match: model = match.groups()[0] continue match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev",
"**kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model,",
"self.mfr == other.mfr and \\ self.model == other.model and self.rev == other.rev except",
"match: quality = match.groups()[0] continue match = re.match(r'modem\\.generic\\.signal-quality\\.recent\\s+:\\s+([a-z]+)', line) if match: recent =",
"import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class",
"operator_code, operator_name): \"\"\" Constructor \"\"\" self.__imsi = imsi # numeric string self.__iccid =",
"return None quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod def",
"*args, **kwargs): return \"Signal:{quality:%s, recent:%s}\" % (self.quality, self.recent) # -------------------------------------------------------------------------------------------------------------------- class SIMList(object): \"\"\"",
"line) if match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match:",
"# ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal): \"\"\" Constructor \"\"\" self.__state = state",
"not None: jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def",
"if match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code",
"match.groups()[0] continue return cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id,",
"__str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" % \\ (self.imsi, self.iccid, self.operator_code,",
"quality(self): return self.__quality @property def recent(self): return self.__recent # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict",
"self.__mfr @property def model(self): return self.__model @property def rev(self): return self.__rev # ----------------------------------------------------------------------------------------------------------------",
"jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid,",
"None imei = None mfr = None model = None rev = None",
"= None for line in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state",
"int self.__recent = recent # bool # ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality",
"import re from collections import OrderedDict from scs_core.data.datum import Datum from scs_core.data.json import",
"self.__modems = modems # array of string def __len__(self): return len(self.__modems) # ----------------------------------------------------------------------------------------------------------------",
"self.imei == other.imei and self.mfr == other.mfr and \\ self.model == other.model and",
"match: imei = match.groups()[0] continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr =",
"jdict: return None quality = jdict.get('quality') recent = jdict.get('recent') return cls(quality, recent) @classmethod",
"# ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict: return None imsi =",
"= re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip() operator_name = None if reported_name",
"match: iccid = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-code\\s+:\\s+([\\d]+)', line) if match: operator_code =",
"self.__operator_name = operator_name # string def __eq__(self, other): try: return self.imsi == other.imsi",
"SIM (Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid :",
"% self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM",
"QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ... modem.3gpp.imei : 867962041294151 \"\"\" #",
"failure # string self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self):",
"return cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id = None",
"and \\ self.model == other.model and self.rev == other.rev except (TypeError, AttributeError): return",
"for line in lines: match = re.match(r'modem\\.generic\\.device-identifier\\s+:\\s+(\\S+)', line) if match: id = match.groups()[0]",
"of string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index]",
"return self.__id @property def imei(self): return self.__imei @property def mfr(self): return self.__mfr @property",
"modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict):",
"self.operator_name == other.operator_name except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self):",
"(TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def id(self): return self.__id @property def",
"scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" #",
"recent = jdict.get('recent') return cls(quality, recent) @classmethod def null_datum(cls): return cls(None, None) #",
"lines): modems = [] for line in lines: match = re.match(r'modem-list.value\\[[\\d]+]\\s+:\\s+([\\S]+)', line) if",
"sim.properties.emergency-numbers.length : 2 sim.properties.emergency-numbers.value[1] : 999 sim.properties.emergency-numbers.value[2] : 00112 example JSON: {\"imsi\": \"123\",",
"jdict['imsi'] = str(self.imsi) jdict['iccid'] = str(self.iccid) jdict['operator-code'] = self.operator_code jdict['operator-name'] = self.operator_name return",
"modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes \"\"\" UNAVAILABLE_STATE = \"unavailable\"",
"\"\"\" Constructor \"\"\" self.__sims = sims # array of string def __len__(self): return",
"def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure, signal):",
"state, failure, signal): \"\"\" Constructor \"\"\" self.__state = state # string self.__failure =",
"= jdict.get('rev') return cls(id, imei, mfr, model, rev) @classmethod def construct_from_mmcli(cls, lines): id",
"match.groups()[0].strip() operator_name = None if reported_name == '--' else reported_name return cls(imsi, iccid,",
"@classmethod def construct_from_mmcli(cls, lines): imsi = None iccid = None operator_code = None",
"continue return cls(state, failure, Signal(quality, recent)) @classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum())",
"SIM(JSONable): \"\"\" classdocs \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod def construct_from_jdict(cls, jdict): if not jdict:",
"= sims # array of string def __len__(self): return len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def",
"JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import re",
"def construct_from_mmcli(cls, lines): id = None imei = None mfr = None model",
"---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] = self.state if self.failure is not",
"'--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match: quality = match.groups()[0]",
"len(self.__sims) # ---------------------------------------------------------------------------------------------------------------- def sim(self, index): return self.__sims[index] def number(self, index): pieces =",
"string def __eq__(self, other): try: return self.id == other.id and self.imei == other.imei",
"match = re.match(r'modem\\.generic\\.revision\\s+:\\s+(\\S+)', line) if match: rev = match.groups()[0] continue return cls(id, imei,",
"construct_from_jdict(cls, jdict): if not jdict: return None imsi = jdict.get('imsi') iccid = jdict.get('iccid')",
"line) if match: state = match.groups()[0] continue match = re.match(r'modem\\.generic\\.state-failed-reason\\s+:\\s+(\\S.*\\S)', line) if match:",
"failure = jdict.get('failure') signal = Signal.construct_from_jdict(jdict.get('signal')) return cls(state, failure, signal) @classmethod def construct_from_mmcli(cls,",
"signal(self): return self.__signal # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict() jdict['state'] = self.state",
"array of string def __len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return",
"self.signal return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\"",
"OrderedDict() jdict['quality'] = self.quality jdict['recent'] = self.recent return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self,",
"__str__(self, *args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier",
"# ---------------------------------------------------------------------------------------------------------------- @property def quality(self): return self.__quality @property def recent(self): return self.__recent #",
"jdict): if not jdict: return None state = jdict.get('state') failure = jdict.get('failure') signal",
"... modem.3gpp.imei : 867962041294151 example JSON: {\"id\": \"3f07553c31ce11715037ac16c24ceddcfb6f7a0b\", \"imei\": \"867962041294151\", \"mfr\": \"QUALCOMM INCORPORATED\",",
": QUALCOMM INCORPORATED modem.generic.model : QUECTEL Mobile Broadband Module modem.generic.revision : EC21EFAR06A01M4G ...",
"import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ----------------------------------------------------------------------------------------------------------------",
"line) if match: modems.append(match.groups()[0]) return cls(modems) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, modems): \"\"\" Constructor",
"self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier : 3f07553c31ce11715037ac16c24ceddcfb6f7a0b modem.generic.manufacturer : QUALCOMM INCORPORATED",
"scs_core.data.datum import Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1]",
"is not None: jdict['failure'] = self.failure jdict['signal'] = self.signal return jdict # ----------------------------------------------------------------------------------------------------------------",
"if match: recent = match.groups()[0] == 'yes' continue return cls(state, failure, Signal(quality, recent))",
"\\ self.operator_code == other.operator_code and self.operator_name == other.operator_name except (TypeError, AttributeError): return False",
"return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" %",
"imei = jdict.get('imei') mfr = jdict.get('mfr') model = jdict.get('model') rev = jdict.get('rev') return",
"jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s, iccid:%s, operator_code:%s, operator_name:%s}\" %",
"self.__operator_code @property def operator_name(self): return self.__operator_name # ---------------------------------------------------------------------------------------------------------------- def as_json(self): jdict = OrderedDict()",
"jdict['operator-name'] = self.operator_name return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"SIM:{imsi:%s,",
"== other.operator_name except (TypeError, AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return",
"rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei, mfr, model, rev): \"\"\" Constructor \"\"\"",
"*args, **kwargs): return \"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr,",
"if match: sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\"",
"re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue match = re.match(r'modem\\.generic\\.model\\s+:\\s+(\\S.*\\S)', line) if",
"example JSON: {\"imsi\": \"123\", \"iccid\": \"456\", \"operator-code\": \"789 012\", \"operator-name\": \"<NAME>\"} \"\"\" import",
"self.__state = state # string self.__failure = failure # string self.__signal = signal",
"*args, **kwargs): return \"ModemConnection:{state:%s, failure:%s, signal:%s}\" % (self.state, self.failure, self.signal) # -------------------------------------------------------------------------------------------------------------------- class",
"Datum from scs_core.data.json import JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0",
"continue match = re.match(r'modem\\.generic\\.manufacturer\\s+:\\s+(\\S.*\\S)', line) if match: mfr = match.groups()[0] continue match =",
"__len__(self): return len(self.__modems) # ---------------------------------------------------------------------------------------------------------------- def modem(self, index): return self.__modems[index] def number(self, index):",
"jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines):",
"\"Modem:{id:%s, imei:%s, mfr:%s, model:%s, rev:%s}\" % \\ (self.id, self.imei, self.mfr, self.model, self.rev) #",
"@classmethod def null_datum(cls): return cls(cls.UNAVAILABLE_STATE, None, Signal.null_datum()) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, state, failure,",
"Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property def failure(self): return self.__failure",
"*args, **kwargs): return \"ModemList:{modems:%s}\" % self.__modems # -------------------------------------------------------------------------------------------------------------------- class Modem(JSONable): \"\"\" modem.generic.device-identifier :",
"null_datum(cls): return cls(None, None) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, quality, recent): \"\"\" Constructor \"\"\"",
"operator_code = match.groups()[0] continue match = re.match(r'sim\\.properties\\.operator-name\\s+:\\s+(\\S.*)', line) if match: reported_name = match.groups()[0].strip()",
"(Subscriber Identity Module) -------------------------------- sim.dbus-path : /org/freedesktop/ModemManager1/SIM/0 sim.properties.imsi : 234104886708667 sim.properties.iccid : 8944110068256270054",
"cls(imsi, iccid, operator_code, operator_name) @classmethod def construct_from_mmcli(cls, lines): imsi = None iccid =",
"AttributeError): return False # ---------------------------------------------------------------------------------------------------------------- @property def imsi(self): return self.__imsi @property def iccid(self):",
"JSONable # -------------------------------------------------------------------------------------------------------------------- class ModemList(object): \"\"\" modem-list.value[1] : /org/freedesktop/ModemManager1/Modem/0 \"\"\" # ---------------------------------------------------------------------------------------------------------------- @classmethod",
"self.model jdict['rev'] = self.rev return jdict # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return",
"self.__signal = signal # Signal # ---------------------------------------------------------------------------------------------------------------- @property def state(self): return self.__state @property",
"sims.append(match.groups()[0]) return cls(sims) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, sims): \"\"\" Constructor \"\"\" self.__sims =",
"connected modem.generic.state-failed-reason : -- modem.generic.signal-quality.value : 67 modem.generic.signal-quality.recent : yes example JSON: {\"state\":",
"= jdict.get('imsi') iccid = jdict.get('iccid') operator_code = jdict.get('operator-code') operator_name = jdict.get('operator-name') return cls(imsi,",
"if reported_failure == '--' else reported_failure continue match = re.match(r'modem\\.generic\\.signal-quality\\.value\\s+:\\s+([\\d]+)', line) if match:",
"continue return cls(id, imei, mfr, model, rev) # ---------------------------------------------------------------------------------------------------------------- def __init__(self, id, imei,",
"in lines: match = re.match(r'modem\\.generic\\.state\\s+:\\s+([a-z]+)', line) if match: state = match.groups()[0] continue match"
] |
[
"0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires",
"the # channels are ordered def _fixData(self, data): for a, b in enumerate(self.c_order):",
"\"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1,",
"1, \"help\": \"Total pixels in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\",",
"3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\",",
"}, { \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", },",
"DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips on devices like the Raspberry",
"\"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2:",
"spi_driver_base import DriverSPIBase, ChannelOrder import os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main",
"WS2801 based LED strips on devices like the Raspberry Pi and BeagleBone\"\"\" def",
"self.gamma = gamma.WS2801 # WS2801 requires gamma correction so we run it through",
"\"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True, \"group\": \"Advanced\" }] } ]",
"num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed <= 0:",
"\"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4:",
"\"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips over a native SPI",
"class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips on devices like the",
"], \"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\",",
"we run it through gamma as the # channels are ordered def _fixData(self,",
"[1, 2, 0], [2, 0, 1], [2, 1, 0] ], \"default\": 0 },",
"in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST =",
"use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma correction so we",
"<reponame>sethshill/final<gh_stars>1-10 from spi_driver_base import DriverSPIBase, ChannelOrder import os from .. import gamma class",
"2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1],",
"an SPI speed no greater than 1MHz or SPI speed was set <=",
"SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\":",
"4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1, 2], [0, 2, 1],",
"import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips on devices",
"WS2801 requires gamma correction so we run it through gamma as the #",
"[2, 0, 1], [2, 1, 0] ], \"default\": 0 }, { \"id\": \"dev\",",
"(SPI Native)\", \"desc\": \"Interface with WS2801 strips over a native SPI port (Pi,",
"greater than 1MHz or SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order,",
"a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in data[b::3]]",
"<= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801",
"gamma as the # channels are ordered def _fixData(self, data): for a, b",
"\"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips",
"0, 1], [2, 1, 0] ], \"default\": 0 }, { \"id\": \"dev\", \"label\":",
"\"\"\"Main driver for WS2801 based LED strips on devices like the Raspberry Pi",
"0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" },",
"for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in",
"\"BGR\" }, \"options_map\": [ [0, 1, 2], [0, 2, 1], [1, 0, 2],",
"\"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips over a native SPI port",
"\"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels in",
"\"options_map\": [ [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2,",
"\"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\":",
"BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1,",
"channels are ordered def _fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs *",
"}, \"options_map\": [ [0, 1, 2], [0, 2, 1], [1, 0, 2], [1,",
"correction so we run it through gamma as the # channels are ordered",
"self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST = [ {",
"\"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels",
"SPISpeed > 1 or SPISpeed <= 0: raise ValueError( \"WS2801 requires an SPI",
"strips over a native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\",",
"\"desc\": \"Interface with WS2801 strips over a native SPI port (Pi, BeagleBone, etc.)\",",
"than 1MHz or SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi,",
"> 1 or SPISpeed <= 0: raise ValueError( \"WS2801 requires an SPI speed",
"v in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\",",
"SPISpeed <= 0: raise ValueError( \"WS2801 requires an SPI speed no greater than",
"Native)\", \"desc\": \"Interface with WS2801 strips over a native SPI port (Pi, BeagleBone,",
"<= 0: raise ValueError( \"WS2801 requires an SPI speed no greater than 1MHz",
"\"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\":",
"and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1",
"speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma =",
"Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\":",
"devices like the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\",",
"\"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips over a",
"SPI speed no greater than 1MHz or SPI speed was set <= 0\")",
"_fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for",
"2, 0], [2, 0, 1], [2, 1, 0] ], \"default\": 0 }, {",
"5: \"BGR\" }, \"options_map\": [ [0, 1, 2], [0, 2, 1], [1, 0,",
"data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v",
"DriverSPIBase, ChannelOrder import os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for",
"c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed <= 0: raise",
"if SPISpeed > 1 or SPISpeed <= 0: raise ValueError( \"WS2801 requires an",
"\"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with",
"= [self.gamma[v] for v in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\":",
"a native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"#",
"2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1,",
"\"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True, \"group\":",
"def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed",
"or SPISpeed <= 0: raise ValueError( \"WS2801 requires an SPI speed no greater",
"\"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0,",
"1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0,",
"dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma correction so we run",
"\"help\": \"Total pixels in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\":",
"in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\":",
"\"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1, 2],",
"dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed <= 0: raise ValueError( \"WS2801",
"1, \"min\": 1, \"help\": \"Total pixels in display.\" }, { \"id\": \"c_order\", \"label\":",
"driver for WS2801 based LED strips on devices like the Raspberry Pi and",
"b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST",
"0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0] ], \"default\":",
"from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips",
"1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]",
"SPISpeed=1): if SPISpeed > 1 or SPISpeed <= 0: raise ValueError( \"WS2801 requires",
"BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or",
"through gamma as the # channels are ordered def _fixData(self, data): for a,",
"[2, 1, 0] ], \"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI Device",
"[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2,",
"gamma correction so we run it through gamma as the # channels are",
"{ \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, {",
"import DriverSPIBase, ChannelOrder import os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver",
"\"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\",",
"Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\",",
"in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": {",
"{ \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True, \"group\": \"Advanced\" }]",
"def _fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v]",
"display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0:",
"= gamma.WS2801 # WS2801 requires gamma correction so we run it through gamma",
"run it through gamma as the # channels are ordered def _fixData(self, data):",
"raise ValueError( \"WS2801 requires an SPI speed no greater than 1MHz or SPI",
"[1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0] ],",
"[{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\":",
"\"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1, 2], [0, 2,",
"native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\",",
"\"min\": 1, \"help\": \"Total pixels in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel",
"{ \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1:",
"gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips on devices like",
"{ 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\"",
"2], [1, 2, 0], [2, 0, 1], [2, 1, 0] ], \"default\": 0",
"or SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed)",
"\"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True, \"group\": \"Advanced\" }] }",
"= [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\",",
"use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed <= 0: raise ValueError(",
"0], [2, 0, 1], [2, 1, 0] ], \"default\": 0 }, { \"id\":",
"data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801",
"SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma correction so we run it",
"1], [2, 1, 0] ], \"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI",
"0: raise ValueError( \"WS2801 requires an SPI speed no greater than 1MHz or",
"\"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use",
".. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED strips on",
"pixels in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\":",
"\"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels in display.\" }, { \"id\":",
"LED strips on devices like the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num,",
"1 or SPISpeed <= 0: raise ValueError( \"WS2801 requires an SPI speed no",
"\"Interface with WS2801 strips over a native SPI port (Pi, BeagleBone, etc.)\", \"params\":",
"SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma",
"0 }, { \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\",",
"\"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\":",
"was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801",
"(Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\":",
"for v in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\":",
"with WS2801 strips over a native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{",
"* 3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST = [ { \"id\":",
"c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma correction so",
"\"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\":",
"DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips over",
"\"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\",",
"\"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels in display.\" }, {",
"Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed",
"self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma correction",
"strips on devices like the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB,",
"\"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\",",
"# WS2801 requires gamma correction so we run it through gamma as the",
"enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] = [self.gamma[v] for v in data[b::3]] MANIFEST = [",
"\"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1, 2], [0, 2, 1], [1,",
"no greater than 1MHz or SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num,",
"import os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based",
"requires gamma correction so we run it through gamma as the # channels",
"__init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed > 1 or SPISpeed <=",
"WS2801 strips over a native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\":",
"etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\":",
"based LED strips on devices like the Raspberry Pi and BeagleBone\"\"\" def __init__(self,",
"2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1,",
"0] ], \"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\":",
"gamma.WS2801 # WS2801 requires gamma correction so we run it through gamma as",
"\"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\",",
"Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\",",
"\"Total pixels in display.\" }, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\",",
"\"type\": \"str\", \"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\",",
"Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if SPISpeed >",
"{ \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface",
"\"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI Device Path\", \"type\": \"str\", \"default\":",
"ordered def _fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3] =",
"like the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1):",
"it through gamma as the # channels are ordered def _fixData(self, data): for",
"[self.gamma[v] for v in data[b::3]] MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801,",
"3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [ [0, 1, 2], [0,",
"MANIFEST = [ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI",
"os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801 based LED",
"as the # channels are ordered def _fixData(self, data): for a, b in",
"[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2,",
"\"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total",
"\"# Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels in display.\"",
"super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 # WS2801 requires gamma",
"ChannelOrder import os from .. import gamma class DriverWS2801(DriverSPIBase): \"\"\"Main driver for WS2801",
"\"default\": 1, \"min\": 1, \"help\": \"Total pixels in display.\" }, { \"id\": \"c_order\",",
"from spi_driver_base import DriverSPIBase, ChannelOrder import os from .. import gamma class DriverWS2801(DriverSPIBase):",
"1MHz or SPI speed was set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev,",
"\"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5:",
"\"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801 strips over a native",
"the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev=\"/dev/spidev0.0\", SPISpeed=1): if",
"}, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True, \"group\": \"Advanced\"",
"are ordered def _fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs * 3:3]",
"on devices like the Raspberry Pi and BeagleBone\"\"\" def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True,",
"speed no greater than 1MHz or SPI speed was set <= 0\") super(DriverWS2801,",
"# channels are ordered def _fixData(self, data): for a, b in enumerate(self.c_order): self._buf[a:self.numLEDs",
"[ { \"id\": \"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\":",
"Pixels\", \"type\": \"int\", \"default\": 1, \"min\": 1, \"help\": \"Total pixels in display.\" },",
"ValueError( \"WS2801 requires an SPI speed no greater than 1MHz or SPI speed",
"requires an SPI speed no greater than 1MHz or SPI speed was set",
"\"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\", 1: \"RBG\", 2: \"GRB\", 3:",
"\"WS2801 requires an SPI speed no greater than 1MHz or SPI speed was",
"port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\": \"# Pixels\", \"type\": \"int\",",
"set <= 0\") super(DriverWS2801, self).__init__(num, c_order=c_order, use_py_spi=use_py_spi, dev=dev, SPISpeed=SPISpeed) self.gamma = gamma.WS2801 #",
"over a native SPI port (Pi, BeagleBone, etc.)\", \"params\": [{ \"id\": \"num\", \"label\":",
"[ [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0],",
"1, 0] ], \"default\": 0 }, { \"id\": \"dev\", \"label\": \"SPI Device Path\",",
"1: \"RBG\", 2: \"GRB\", 3: \"GBR\", 4: \"BRG\", 5: \"BGR\" }, \"options_map\": [",
"for WS2801 based LED strips on devices like the Raspberry Pi and BeagleBone\"\"\"",
"}, { \"id\": \"c_order\", \"label\": \"Channel Order\", \"type\": \"combo\", \"options\": { 0: \"RGB\",",
"so we run it through gamma as the # channels are ordered def",
"\"default\": \"/dev/spidev0.0\", }, { \"id\": \"use_py_spi\", \"label\": \"Use PySPI\", \"type\": \"bool\", \"default\": True,",
"\"WS2801\", \"class\": DriverWS2801, \"type\": \"driver\", \"display\": \"WS2801 (SPI Native)\", \"desc\": \"Interface with WS2801"
] |
[
"NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\",",
"Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\",",
"Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\",",
"Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\",",
"Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)),",
"Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind =",
"( MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta",
"Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()),",
"NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)),",
"Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind =",
"Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False),",
"Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine):",
"Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta =",
"Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user =",
"= migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False,",
"NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)),",
"Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\",",
"DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()),",
"nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()),",
") user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table(\"user\",",
"nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user =",
"meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)),",
"upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table( \"user\", meta, Column(\"id\",",
"migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True),",
"Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\",",
"\"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\",",
"Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False),",
"def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table(\"user\", meta, autoload=True)",
"DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table(",
"user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\",",
"Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)),",
"= Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255),",
"Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind",
"Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind",
"nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()),",
"from sqlalchemy import ( MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, )",
"NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta",
"MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta =",
"unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\",",
") def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table( \"user\",",
"Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()),",
"user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table(\"user\", meta,",
"DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(),",
"<gh_stars>0 from sqlalchemy import ( MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime,",
"NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def",
"meta = MetaData() meta.bind = migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer,",
"DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), )",
"primary_key=True), Column(\"email\", NVARCHAR(255), nullable=False, unique=True), Column(\"password\", NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\",",
"meta.bind = migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\", NVARCHAR(255),",
"downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table(\"user\", meta, autoload=True) user.drop()",
"sqlalchemy import ( MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def",
"NVARCHAR(255), nullable=False), Column(\"first_name\", NVARCHAR(255)), Column(\"last_name\", NVARCHAR(255)), Column(\"active\", Boolean()), Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\",",
"def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user = Table( \"user\", meta,",
"= MetaData() meta.bind = migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True),",
"MetaData() meta.bind = migrate_engine user = Table( \"user\", meta, Column(\"id\", Integer, primary_key=True), Column(\"email\",",
"NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData()",
"DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user",
"Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\", Integer()), Column(\"created_date\", DateTime(), nullable=False), ) user.create()",
"Column(\"confirmed_at\", DateTime()), Column(\"last_login_at\", DateTime()), Column(\"current_login_at\", DateTime()), Column(\"last_name\", NVARCHAR(255)), Column(\"last_login_ip\", NVARCHAR(255)), Column(\"current_login_ip\", NVARCHAR(255)), Column(\"login_count\",",
"import ( MetaData, Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine):",
"NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine",
"Table, Column, Integer, NVARCHAR, DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData()",
"DateTime, Boolean, DateTime, ) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine user",
"Column(\"created_date\", DateTime(), nullable=False), ) user.create() def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine"
] |
[
"from .designMethods import MARSInput, ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app",
"import MainApplication, ResultWriter # noqa: F401 __all__ = [\"MARSInput\", \"Computation\", \"LoadCollectivePrediction\", \"MainApplication\", \"ResultWriter\"]",
".designMethods import MARSInput, ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app import",
"<reponame>tum-fml/marsDemonstrator from .designMethods import MARSInput, ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from",
"F401 from .main_app import MainApplication, ResultWriter # noqa: F401 __all__ = [\"MARSInput\", \"Computation\",",
"LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app import MainApplication, ResultWriter # noqa:",
"from .main_app import MainApplication, ResultWriter # noqa: F401 __all__ = [\"MARSInput\", \"Computation\", \"LoadCollectivePrediction\",",
"load_all_gps, InputFileError # noqa: F401 from .main_app import MainApplication, ResultWriter # noqa: F401",
"ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app import MainApplication, ResultWriter #",
".main_app import MainApplication, ResultWriter # noqa: F401 __all__ = [\"MARSInput\", \"Computation\", \"LoadCollectivePrediction\", \"MainApplication\",",
"InputFileError # noqa: F401 from .main_app import MainApplication, ResultWriter # noqa: F401 __all__",
"noqa: F401 from .main_app import MainApplication, ResultWriter # noqa: F401 __all__ = [\"MARSInput\",",
"# noqa: F401 from .main_app import MainApplication, ResultWriter # noqa: F401 __all__ =",
"MARSInput, ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app import MainApplication, ResultWriter",
"import MARSInput, ENComputation, LoadCollectivePrediction, load_all_gps, InputFileError # noqa: F401 from .main_app import MainApplication,"
] |
[
"from anytree.exporter import JsonExporter def calc_tree(root): for node in PostOrderIter(root): config = node.config",
"def build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name",
"= str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if",
"hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root = node_status node.name = str(node.config)",
"node_status = node.config.is_root node.config.is_root = True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json",
"from anytree import PostOrderIter from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import",
"JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root =",
"node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root = node_status",
"node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash)",
"anytree import PostOrderIter from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import hashlib",
"in node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root):",
"exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root = node_status node.name =",
"import Context import hashlib from anytree.exporter import JsonExporter def calc_tree(root): for node in",
"Context import hashlib from anytree.exporter import JsonExporter def calc_tree(root): for node in PostOrderIter(root):",
"JsonExporter def calc_tree(root): for node in PostOrderIter(root): config = node.config configs_child = [node_child.config",
"exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node)",
"import hashlib from anytree.exporter import JsonExporter def calc_tree(root): for node in PostOrderIter(root): config",
"node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root): node_status",
"context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root): node_status =",
"in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name = str(node.config) exporter =",
"pydnameth.model.context import Context import hashlib from anytree.exporter import JsonExporter def calc_tree(root): for node",
"PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name = str(node.config) exporter = JsonExporter(sort_keys=True)",
"configs_child = [node_child.config for node_child in node.children] context = Context(config) context.pipeline(config, configs_child) def",
"anytree.exporter import JsonExporter def calc_tree(root): for node in PostOrderIter(root): config = node.config configs_child",
"= node.config.is_root node.config.is_root = True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json =",
"import PostOrderIter from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import hashlib from",
"= [node_child.config for node_child in node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root):",
"node_child in node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in",
"<filename>pydnameth/model/tree.py from anytree import PostOrderIter from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context",
"def calc_tree(root): for node in PostOrderIter(root): config = node.config configs_child = [node_child.config for",
"= node.config configs_child = [node_child.config for node_child in node.children] context = Context(config) context.pipeline(config,",
"node in PostOrderIter(root): config = node.config configs_child = [node_child.config for node_child in node.children]",
"= True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash =",
"= JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root",
"for node in PostOrderIter(root): config = node.config configs_child = [node_child.config for node_child in",
"[node_child.config for node_child in node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for",
"PostOrderIter from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import hashlib from anytree.exporter",
"from pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import hashlib from anytree.exporter import",
"PostOrderIter(root): config = node.config configs_child = [node_child.config for node_child in node.children] context =",
"import save_info from pydnameth.model.context import Context import hashlib from anytree.exporter import JsonExporter def",
"for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name = str(node.config)",
"pydnameth.infrastucture.save.info import save_info from pydnameth.model.context import Context import hashlib from anytree.exporter import JsonExporter",
"from pydnameth.model.context import Context import hashlib from anytree.exporter import JsonExporter def calc_tree(root): for",
"import JsonExporter def calc_tree(root): for node in PostOrderIter(root): config = node.config configs_child =",
"for node_child in node.children] context = Context(config) context.pipeline(config, configs_child) def build_tree(root): for node",
"config = node.config configs_child = [node_child.config for node_child in node.children] context = Context(config)",
"node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name = str(node.config) exporter",
"hashlib from anytree.exporter import JsonExporter def calc_tree(root): for node in PostOrderIter(root): config =",
"node.config.is_root node.config.is_root = True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8')",
"True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest()",
"= exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run: save_info(node) node.config.is_root = node_status node.name",
"build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True node.name =",
"calc_tree(root): for node in PostOrderIter(root): config = node.config configs_child = [node_child.config for node_child",
"node.config configs_child = [node_child.config for node_child in node.children] context = Context(config) context.pipeline(config, configs_child)",
"configs_child) def build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root = True",
"node.config.is_root = True node.name = str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash",
"save_info from pydnameth.model.context import Context import hashlib from anytree.exporter import JsonExporter def calc_tree(root):",
"context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root =",
"Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root node.config.is_root",
"= Context(config) context.pipeline(config, configs_child) def build_tree(root): for node in PostOrderIter(root): node_status = node.config.is_root",
"in PostOrderIter(root): config = node.config configs_child = [node_child.config for node_child in node.children] context",
"str(node.config) exporter = JsonExporter(sort_keys=True) node_json = exporter.export(node).encode('utf-8') hash = hashlib.md5(node_json).hexdigest() node.config.set_hash(hash) if node.config.is_run:"
] |
[
"import get from bs4 import BeautifulSoup import pandas as pd class Stock: def",
"if key in indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio',",
"element in indicators if (element in shown) == True] for index in range(len(valuations)):",
"the fundamental indicators indicators = [element.text for element in html_table.find_all('h3')] valuations = [element.text",
"the indicador name on site, however that are some duplicates h3 tags that",
"'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators):",
"Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE',",
"return {key: values for (key, values) in self.get_all_indicators().items() if key in indicators} class",
"def __init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html =",
"html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the",
"the same indicador, to avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit',",
"price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items()",
"{key: indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for",
"'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda',",
"/ Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') # there is a",
"a pŕoblem with this indicators, because the html source get more h3 tags",
"= ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html,",
"Líquida') return {key: values for (key, values) in super.get_all_indicators().items() if key in indicators}",
"key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\",",
"tags show the indicador name on site, however that are some duplicates h3",
"Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA',",
"indicators, because the html source get more h3 tags here, and some #",
"for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in",
"indicators if (element in shown) == True] for index in range(len(valuations)): value =",
"companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def",
"Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators = [element for",
"= BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators)",
"{ 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem",
"== True] for index in range(len(valuations)): value = valuations[index] if '%' in value:",
"3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem",
"= Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators,",
"for (key, values) in self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self): indicators",
"Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida /",
"to the same indicador, to avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda',",
"{key: values for (key, values) in super.get_all_indicators().items() if key in indicators} @property def",
"5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}}",
"petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators())",
"Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC',",
"exactly table with the fundamental indicators indicators = [element.text for element in html_table.find_all('h3')]",
"self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table",
"indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key,",
"10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos /",
"'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida",
"'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators = [element for element",
"show the indicador name on site, however that are some duplicates h3 tags",
"5 Anos') indicators = [element for element in indicators if (element in shown)",
"2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5},",
"same indicador, to avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo',",
"'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE':",
"\"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr",
"in indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for",
"if key in indicators} class B3: def __repr__(self): return 'Brazilian Trader object' def",
"(key, values) in self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self): indicators =",
"'''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc =",
"that are not showm in the front end, but exists and # refers",
"indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column",
"'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas =",
"source get more h3 tags here, and some # indicadors are not the",
"in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\",",
"= ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values for (key, values)",
"'.') value = float(value) except ValueError: value = 'Not avaiable' valuations[index] = value",
"'Passivos / Ativos') indicators = {key: indicators[key] for key in chosen_metrics} metrics_df =",
"Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida",
"Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n',",
"in self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida",
"element in html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')] if len(indicators) !=",
"'%' in value: value = value[:-1] try: value = value.replace(',', '.') value =",
"Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key] for",
"= get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly",
"\"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\": # Testing area '''request =",
"= get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3')",
"are not showm in the front end, but exists and # refers to",
"= [element.text for element in html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')]",
"Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n', clas.profit_indicators, '\\n', clas.debt_indicators)'''",
"'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR",
"'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR",
"is a pŕoblem with this indicators, because the html source get more h3",
"= {key: indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"])",
"\"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\": #",
"'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta',",
"'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15,",
"object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida')",
"Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') # there is",
"if key in indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return",
"fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators",
"'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values for (key, values) in super.get_all_indicators().items()",
"('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio',",
"debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos /",
"Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE',",
"'P/L', 'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items() if key in indicators}",
"__repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self):",
"the front end, but exists and # refers to the same indicador, to",
"name on site, however that are some duplicates h3 tags that are not",
"in range(len(valuations)): value = valuations[index] if '%' in value: value = value[:-1] try:",
"indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida",
"indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values for (key,",
"avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR',",
"class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators =",
"{key:values for (key, values) in self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self):",
"exists and # refers to the same indicador, to avoid errors, the shown",
"'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida",
"super.get_all_indicators().items() if key in indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo')",
"self._points = 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo':",
"h3 tags that are not showm in the front end, but exists and",
"= value.replace(',', '.') value = float(value) except ValueError: value = 'Not avaiable' valuations[index]",
"html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3 tags show the indicador name",
"def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values",
"class B3: def __repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx')",
"('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') # there",
"/ EBITDA', 'Passivos / Ativos') # there is a pŕoblem with this indicators,",
"more h3 tags here, and some # indicadors are not the same return",
"'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key] for key",
"'Margem Líquida') return {key: values for (key, values) in super.get_all_indicators().items() if key in",
"from requests import get from bs4 import BeautifulSoup import pandas as pd class",
"this indicators, because the html source get more h3 tags here, and some",
"the html source get more h3 tags here, and some # indicadors are",
"/ Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key]",
"in indicators if (element in shown) == True] for index in range(len(valuations)): value",
"profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values for",
"not showm in the front end, but exists and # refers to the",
"analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo',",
"/ Ativos') indicators = {key: indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators,",
"self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker'])",
"EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key] for key in chosen_metrics} metrics_df",
"15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1,",
"h3 tags show the indicador name on site, however that are some duplicates",
"Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA':",
"Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4')",
"@property def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA',",
"tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker):",
"'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida",
"metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \"",
"errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro',",
"Ativos') # there is a pŕoblem with this indicators, because the html source",
"values) in self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self): indicators = ('Dívida",
"(key, values) in super.get_all_indicators().items() if key in indicators} @property def price_indicators(self): indicators =",
"'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA',",
"cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n', clas.profit_indicators,",
"tags here, and some # indicadors are not the same return {key: values",
"'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem",
"f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals =",
"key in indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida",
"try: value = value.replace(',', '.') value = float(value) except ValueError: value = 'Not",
"'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos')",
"{key: values for (key, values) in self.get_all_indicators().items() if key in indicators} class B3:",
"soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the fundamental indicators indicators = [element.text",
"def overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return",
"self._ticker = ticker self._points = 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3,",
"'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock):",
"'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the fundamental indicators",
"self.get_all_indicators().items() if key in indicators} class B3: def __repr__(self): return 'Brazilian Trader object'",
"refers to the same indicador, to avoid errors, the shown = ('P/VP', 'P/L',",
"'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors':",
"def __repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def",
"Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida",
"BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the fundamental",
"area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc",
"'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos',",
"overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry']",
"def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def companies_list(self):",
"soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with",
"and some # indicadors are not the same return {key: values for (key,",
"avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def",
"{ 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self,",
"indicators = {key: indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current",
"Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida',",
"\"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\": # Testing",
"[element.text for element in html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3 tags",
"'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms",
"that are some duplicates h3 tags that are not showm in the front",
"for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if",
"pandas as pd class Stock: def __init__(self, ticker): self._ticker = ticker self._url =",
"value: value = value[:-1] try: value = value.replace(',', '.') value = float(value) except",
"front end, but exists and # refers to the same indicador, to avoid",
"= [element for element in indicators if (element in shown) == True] for",
"return 'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return",
"= ticker self._points = 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L':",
"Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio /",
"'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda',",
"'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT',",
"'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida",
"Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property",
"and # refers to the same indicador, to avoid errors, the shown =",
"however that are some duplicates h3 tags that are not showm in the",
"'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA',",
"print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n', clas.profit_indicators, '\\n', clas.debt_indicators)''' print(B3().get_by_industry('Materiais Básicos'))",
"the h3 tags show the indicador name on site, however that are some",
"[element.text for element in html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')] if",
"Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5",
"def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values) in",
"self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup =",
"value = float(value) except ValueError: value = 'Not avaiable' valuations[index] = value fundamental_indicators",
"columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] =",
"= 'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class",
"industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker =",
"= dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>'",
"if len(indicators) != len(valuations): # the h3 tags show the indicador name on",
"'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida',",
"Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker self._points",
"[element for element in indicators if (element in shown) == True] for index",
"EBITDA', 'Passivos / Ativos') # there is a pŕoblem with this indicators, because",
"orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column]",
"Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators = {key:",
"in self.get_all_indicators().items() if key in indicators} class B3: def __repr__(self): return 'Brazilian Trader",
"dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property",
"return {key: values for (key, values) in super.get_all_indicators().items() if key in indicators} @property",
"# the h3 tags show the indicador name on site, however that are",
"== industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker",
"= ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida /",
"'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio',",
"'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos /",
"for (key, values) in self.get_all_indicators().items() if key in indicators} class B3: def __repr__(self):",
"return {key:values for (key, values) in self.get_all_indicators().items() if key in indicators} @property def",
"= { 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem",
"print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3')",
"Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators =",
"if '%' in value: value = value[:-1] try: value = value.replace(',', '.') value",
"'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC':",
"('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key: values for (key, values) in",
"self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker'])",
"<filename>B3Analyzer/utilities.py from requests import get from bs4 import BeautifulSoup import pandas as pd",
"indicators = [element for element in indicators if (element in shown) == True]",
"html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')] if len(indicators) != len(valuations): #",
"valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def",
"Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series()",
"are not the same return {key: values for (key, values) in self.get_all_indicators().items() if",
"'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC',",
"as pd class Stock: def __init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}'",
"EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente',",
"the same return {key: values for (key, values) in self.get_all_indicators().items() if key in",
"if __name__ == \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request,",
"valuations[index] if '%' in value: value = value[:-1] try: value = value.replace(',', '.')",
"= pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def",
"site, however that are some duplicates h3 tags that are not showm in",
"@property def overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry):",
"industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def",
"Líquida / EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key] for key in",
"return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super):",
"BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas",
"Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') # there is a pŕoblem",
"+Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\": # Testing area '''request",
"values for (key, values) in super.get_all_indicators().items() if key in indicators} @property def price_indicators(self):",
"= Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n', clas.profit_indicators, '\\n',",
"__name__ == \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser')",
"import BeautifulSoup import pandas as pd class Stock: def __init__(self, ticker): self._ticker =",
"= ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq',",
"duplicates h3 tags that are not showm in the front end, but exists",
"'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators",
"to avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT',",
"there is a pŕoblem with this indicators, because the html source get more",
"for element in indicators if (element in shown) == True] for index in",
"= soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the fundamental indicators indicators =",
"'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio",
"return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self,",
"chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida",
"ticker self._points = 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L': 20,",
"indicators} class B3: def __repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms =",
"'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators = [element",
"Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida /",
"but exists and # refers to the same indicador, to avoid errors, the",
"1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics =",
"__init__(self, ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals = { 'price_indicators': {",
"def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer:",
"{ 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': {",
"Stock: def __init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html",
"/ Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators",
"= pd.Series() if __name__ == \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup",
"key in indicators} class B3: def __repr__(self): return 'Brazilian Trader object' def __init__(self):",
"__repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem",
"# indicadors are not the same return {key: values for (key, values) in",
"get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators())",
"def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L',",
"'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida",
"/ EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5",
"def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer",
"Anos', 'CAGR Lucros 5 Anos') indicators = [element for element in indicators if",
"range(len(valuations)): value = valuations[index] if '%' in value: value = value[:-1] try: value",
"print(cvc.get_all_indicators()) print(cvc.get_all_indicators()) print(petr.profit_indicators) clas = Stock('cvcb3') print(clas.get_all_indicators()) print(clas.price_indicators, '\\n', clas.profit_indicators, '\\n', clas.debt_indicators)''' print(B3().get_by_industry('Materiais",
"'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro",
"value = value.replace(',', '.') value = float(value) except ValueError: value = 'Not avaiable'",
"= valuations[index] if '%' in value: value = value[:-1] try: value = value.replace(',',",
"= ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items() if key",
"Receitas 5 Anos', 'CAGR Lucros 5 Anos') indicators = [element for element in",
"value = valuations[index] if '%' in value: value = value[:-1] try: value =",
"def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker self._points =",
"value.replace(',', '.') value = float(value) except ValueError: value = 'Not avaiable' valuations[index] =",
"('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items() if key in",
"indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos')",
"chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\",",
"pŕoblem with this indicators, because the html source get more h3 tags here,",
"tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return",
"# select the exactly table with the fundamental indicators indicators = [element.text for",
"if (element in shown) == True] for index in range(len(valuations)): value = valuations[index]",
"get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object'",
"values) in super.get_all_indicators().items() if key in indicators} @property def price_indicators(self): indicators = ('P/VP',",
"5 Anos', 'CAGR Lucros 5 Anos') indicators = [element for element in indicators",
"'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem",
"3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8,",
"B3: def __repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property",
"def __init__(self, ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals = { 'price_indicators':",
"ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup",
"1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida', 'P/VP',",
"value = value[:-1] try: value = value.replace(',', '.') value = float(value) except ValueError:",
"ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser')",
"'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos':",
"here, and some # indicadors are not the same return {key: values for",
"pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self,",
"@property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values)",
"h3 tags here, and some # indicadors are not the same return {key:",
"== \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\"))",
"some # indicadors are not the same return {key: values for (key, values)",
"EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos',",
"showm in the front end, but exists and # refers to the same",
"in indicators} class B3: def __repr__(self): return 'Brazilian Trader object' def __init__(self): self._firms",
"html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the fundamental indicators indicators",
"'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem",
"not the same return {key: values for (key, values) in self.get_all_indicators().items() if key",
"values) in self.get_all_indicators().items() if key in indicators} class B3: def __repr__(self): return 'Brazilian",
"= ('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') #",
"Líquida / EBITDA', 'Passivos / Ativos') # there is a pŕoblem with this",
"/ EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez",
"Lucros 5 Anos') indicators = [element for element in indicators if (element in",
"soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr = Data(ticker='petr4') cvc = Data('cvcb3') print(cvc.get_all_indicators()) print(cvc.get_all_indicators())",
"Ativos') indicators = {key: indicators[key] for key in chosen_metrics} metrics_df = pd.DataFrame.from_dict(indicators, orient='index',",
"len(valuations): # the h3 tags show the indicador name on site, however that",
"select the exactly table with the fundamental indicators indicators = [element.text for element",
"'Margem Ebitda', 'Margem Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida",
"<{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return",
"class Stock: def __init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self):",
"/ EBITDA', 'Passivos / Ativos') indicators = {key: indicators[key] for key in chosen_metrics}",
"'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida /",
"'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit',",
"return self._firms @property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] ==",
"(key, values) in self.get_all_indicators().items() if key in indicators} class B3: def __repr__(self): return",
"metrics_df[column] = pd.Series() if __name__ == \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text",
"__repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker self._points = 0",
"self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': {",
"\" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\": # Testing area",
"'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def",
"'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida",
"in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ ==",
"in shown) == True] for index in range(len(valuations)): value = valuations[index] if '%'",
"= value[:-1] try: value = value.replace(',', '.') value = float(value) except ValueError: value",
"valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self):",
"values for (key, values) in self.get_all_indicators().items() if key in indicators} class B3: def",
"'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos /",
"'Margem Ebitda', 'Margem Líquida') return {key: values for (key, values) in super.get_all_indicators().items() if",
"__init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def companies_list(self): return",
"= 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2},",
"on site, however that are some duplicates h3 tags that are not showm",
"f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0]",
"get more h3 tags here, and some # indicadors are not the same",
"/ Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos',",
"fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock object",
"shown) == True] for index in range(len(valuations)): value = valuations[index] if '%' in",
"float(value) except ValueError: value = 'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators,",
"same return {key: values for (key, values) in self.get_all_indicators().items() if key in indicators}",
"'Dívida Líquida / EBITDA', 'Passivos / Ativos') # there is a pŕoblem with",
"indicador, to avoid errors, the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda',",
"20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10,",
"BeautifulSoup import pandas as pd class Stock: def __init__(self, ticker): self._ticker = ticker",
"(\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__ == \"__main__\":",
"True] for index in range(len(valuations)): value = valuations[index] if '%' in value: value",
"/ Ativos') # there is a pŕoblem with this indicators, because the html",
"for (key, values) in super.get_all_indicators().items() if key in indicators} @property def price_indicators(self): indicators",
"class Analyzer: def __repr__(self): return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker",
"'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos') indicators =",
"in html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3 tags show the indicador",
"'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA',",
"for index in range(len(valuations)): value = valuations[index] if '%' in value: value =",
"def __repr__(self): return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC',",
"are some duplicates h3 tags that are not showm in the front end,",
"value = 'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators",
"@property def companies_list(self): return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class",
"element in html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3 tags show the",
"Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida /",
"Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas",
"table with the fundamental indicators indicators = [element.text for element in html_table.find_all('h3')] valuations",
"indicador name on site, however that are some duplicates h3 tags that are",
"# refers to the same indicador, to avoid errors, the shown = ('P/VP',",
"(element in shown) == True] for index in range(len(valuations)): value = valuations[index] if",
"= value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return",
"'Giro Ativos', 'ROE', 'ROA', 'ROIC', 'LPA', 'VPA', 'Dívida Líquida / Patrimônio', 'Dívida Líquida",
"requests import get from bs4 import BeautifulSoup import pandas as pd class Stock:",
"with this indicators, because the html source get more h3 tags here, and",
"= [element.text for element in html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3",
"!= len(valuations): # the h3 tags show the indicador name on site, however",
"'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida': 15, 'Margem Líquida':",
"('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ Liq', 'Margem",
"value fundamental_indicators = dict(zip(indicators, valuations)) return fundamental_indicators class Firm(Stock): def __repr__(self): return f'BrazilianStock",
"'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE',",
"Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos / Ativos',",
"/ Ativos', 'Passivos / Ativos', 'Liquidez Corrente', 'CAGR Receitas 5 Anos', 'CAGR Lucros",
"'Passivos / Ativos') # there is a pŕoblem with this indicators, because the",
"in super.get_all_indicators().items() if key in indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L',",
"/ Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem",
"= float(value) except ValueError: value = 'Not avaiable' valuations[index] = value fundamental_indicators =",
"end, but exists and # refers to the same indicador, to avoid errors,",
"key in indicators} @property def price_indicators(self): indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values",
"valuations = [element.text for element in html_table.find_all('strong')] if len(indicators) != len(valuations): # the",
"indicadors are not the same return {key: values for (key, values) in self.get_all_indicators().items()",
"html source get more h3 tags here, and some # indicadors are not",
"get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table",
"'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos",
"pd.Series() if __name__ == \"__main__\": # Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup =",
"Anos') indicators = [element for element in indicators if (element in shown) ==",
"some duplicates h3 tags that are not showm in the front end, but",
"# Testing area '''request = get('https://statusinvest.com.br/acoes/cvcb3').text soup = BeautifulSoup(request, 'html.parser') print(soup.select(\"div.width-auto:nth-child(2)\")) petr =",
"in value: value = value[:-1] try: value = value.replace(',', '.') value = float(value)",
"ValueError: value = 'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations)) return",
"return f'FundamentalAnalyzer object' def __init__(self, ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals",
"__init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text",
"import pandas as pd class Stock: def __init__(self, ticker): self._ticker = ticker self._url",
"Liq', 'Margem Bruta', 'Margem Ebitda', 'Margem Ebit', 'Margem Líquida', 'Giro Ativos', 'ROE', 'ROA',",
"'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items() if key in indicators} @property",
"from bs4 import BeautifulSoup import pandas as pd class Stock: def __init__(self, ticker):",
"f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem",
"indicators = [element.text for element in html_table.find_all('h3')] valuations = [element.text for element in",
"Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3, 'Passivos / Ativos': 1}} def analyze_metrics(self, indicators): chosen_metrics",
"the shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo",
"Patrimônio', 'Dívida Líquida / EBITDA', 'Dívida Líquida / EBIT', 'Patrimônio / Ativos', 'Passivos",
"the exactly table with the fundamental indicators indicators = [element.text for element in",
"in indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida",
"object' def __init__(self): self._firms = pd.read_excel('data/B3_list.xlsx') @property def overall_report(self): return self._firms @property def",
"tags that are not showm in the front end, but exists and #",
"self.get_all_indicators().items() if key in indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida /",
"index in range(len(valuations)): value = valuations[index] if '%' in value: value = value[:-1]",
"@property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda', 'Margem Líquida') return {key:",
"for element in html_table.find_all('strong')] if len(indicators) != len(valuations): # the h3 tags show",
"for element in html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')] if len(indicators)",
"return f'BrazilianStock object <{self._ticker.upper()}>' @property def profit_indicators(super): indicators = ('ROE', 'ROIC', 'Margem Ebitda',",
"fundamental indicators indicators = [element.text for element in html_table.find_all('h3')] valuations = [element.text for",
"= pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\",",
"except ValueError: value = 'Not avaiable' valuations[index] = value fundamental_indicators = dict(zip(indicators, valuations))",
"because the html source get more h3 tags here, and some # indicadors",
"Líquida', 'P/VP', 'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos",
"{ 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators': { 'Margem Ebtida':",
"def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos",
"in the front end, but exists and # refers to the same indicador,",
"shown = ('P/VP', 'P/L', 'P/Ebitda', 'P/Ebit', 'P/Ativo', 'EV/Ebitda', 'EV/EBIT', 'PSR', 'P/Cap.Giro', 'P/Ativo Circ",
"value[:-1] try: value = value.replace(',', '.') value = float(value) except ValueError: value =",
"'CAGR Lucros 5 Anos') indicators = [element for element in indicators if (element",
"bs4 import BeautifulSoup import pandas as pd class Stock: def __init__(self, ticker): self._ticker",
"= BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select the exactly table with the",
"get from bs4 import BeautifulSoup import pandas as pd class Stock: def __init__(self,",
"ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals = { 'price_indicators': { 'P/VP':",
"def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] #",
"get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table = soup.select(\"div.width-auto:nth-child(2)\")[0] # select",
"in html_table.find_all('h3')] valuations = [element.text for element in html_table.find_all('strong')] if len(indicators) != len(valuations):",
"Ebitda', 'Margem Líquida') return {key: values for (key, values) in super.get_all_indicators().items() if key",
"return tuple(self._firms['Ticker']) def get_by_industry(self, industry): return tuple(self._firms[self._firms['Industry'] == industry]['Ticker']) class Analyzer: def __repr__(self):",
"len(indicators) != len(valuations): # the h3 tags show the indicador name on site,",
"with the fundamental indicators indicators = [element.text for element in html_table.find_all('h3')] valuations =",
"0 self._basic_fundamentals = { 'price_indicators': { 'P/VP': 3, 'P/L': 20, 'P/Ativo': 2}, 'profit_indicators':",
"# there is a pŕoblem with this indicators, because the html source get",
"= f'https://statusinvest.com.br/acoes/{self._ticker}' def get_all_indicators(self): html = get(self._url).text soup = BeautifulSoup(html, 'html.parser') html_table =",
"indicators} @property def debt_indicators(self): indicators = ('Dívida Líquida / Patrimônio', 'Dívida Líquida /",
"indicators indicators = [element.text for element in html_table.find_all('h3')] valuations = [element.text for element",
"8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim': 1, 'Dívida Líq/EBITDA': 3,",
"pd class Stock: def __init__(self, ticker): self._ticker = ticker self._url = f'https://statusinvest.com.br/acoes/{self._ticker}' def",
"object' def __init__(self, ticker): self._ticker = ticker self._points = 0 self._basic_fundamentals = {",
"'P/L', 'P/Ativo', 'Dívida Líquida / Patrimônio', 'Dívida Líquida / EBITDA', 'Passivos / Ativos')",
"pd.DataFrame.from_dict(indicators, orient='index', columns=[\"Current Value\"]) for column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"):",
"column in (\"Min\", \"Max\", \"Weigh\", \" +Points\", \"-Points\"): metrics_df[column] = pd.Series() if __name__",
"Ebtida': 15, 'Margem Líquida': 8, 'ROE': 10, 'ROIC': 5}, 'debt_indicadors': { 'Dívida Líq/Patrim':",
"indicators = ('P/VP', 'P/L', 'P/Ativo') return {key:values for (key, values) in self.get_all_indicators().items() if"
] |
[] |
[] |
[
"from collections import deque import random import gym # from typing import List",
"it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size - (kernel_size",
"= 1/.((episode/10)+1) done = False step_count = 0 state = self.env.reset() while not",
"values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber loss loss",
"input connections depends on output of conv2d layers # and therefore the input",
"F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython",
"device=device) # Observe new state last_screen = current_screen current_screen = get_screen() if not",
"Dense, Reshape, Flatten, Dropout, Activation from keras import regularizers from keras.models import Model",
"self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY",
"w, outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1 =",
"# detailed explanation). This converts batch-array of Transitions # to Transition of batch-arrays.",
"w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 =",
"# self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY",
"Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes",
"0 state = self.env.reset() while not done: state = np.reshape(state, (1,self.obs)) if np.random.rand()",
"def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def",
"32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x =",
"optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for",
"state state = next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations() break if",
">= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001)",
"range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count = 0 state = self.env.reset()",
"def __init__(self, discount=0.99, batch_size = 64, max_episodes = 300): self.env = gym.make('CartPole-v0') #",
"gym # from typing import List import argparse class DQN(): def __init__(self, discount=0.99,",
"state would've been the one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s:",
"convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x)))",
"Select and perform an action action = select_action(state) _, reward, done, _ =",
"self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32,",
"rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on",
"x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1))",
"# self.target_Qnet state = next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from",
"def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) #",
"# Initialize the environment and state env.reset() last_screen = get_screen() current_screen = get_screen()",
"from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation from keras import regularizers",
"torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask]",
"not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value =",
"step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state step_count +=1 print(\"Episode:",
"import Input, Dense, Reshape, Flatten, Dropout, Activation from keras import regularizers from keras.models",
"plt.ion() # if gpu is to be used device = torch.device(\"cuda\" if torch.cuda.is_available()",
"batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9",
"elements # (a final state would've been the one after which simulation ended)",
"last_screen else: next_state = None memory.push(state, action, next_state, reward) # Move to the",
"select_action(state) _, reward, done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe",
"TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\",",
"layers # and therefore the input image size, so compute it. def conv2d_size_out(size,",
"{}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation from keras",
"plot them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means",
"which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device,",
"\"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False)",
"new state last_screen = current_screen current_screen = get_screen() if not done: next_state =",
"= self.env.step(action) if done: reward = -1 buffer.push((state, action, reward, next_state)) if len(buffer)",
"def train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done",
"if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def",
"= nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5,",
"def __init__(self, h, w, outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h, w,",
"self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes",
"Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask of non-final states",
"torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T env =",
"for s in batch.next_state if s is not None]) state_batch = torch.cat(batch.state) action_batch",
"capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args):",
"import numpy as np # from collections import deque import random import gym",
"detailed explanation). This converts batch-array of Transitions # to Transition of batch-arrays. batch",
"outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 =",
"0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position]",
"= self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t =",
"train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done =",
"= durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a",
"if gpu is to be used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")",
"self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def",
"force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES",
"self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size =",
"explanation). This converts batch-array of Transitions # to Transition of batch-arrays. batch =",
"training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory)",
"buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states",
"(next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))",
"nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x =",
"for i_episode in range(num_episodes): # Initialize the environment and state env.reset() last_screen =",
"in range(num_episodes): # Initialize the environment and state env.reset() last_screen = get_screen() current_screen",
"typing import List import argparse class DQN(): def __init__(self, discount=0.99, batch_size = 64,",
"random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch]) actions = np.array([x[1] for",
"as plt from collections import namedtuple from itertools import count from PIL import",
"self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args): \"\"\"Saves",
"PIL import Image import torch import torch.nn as nn import torch.optim as optim",
"kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 =",
"self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY",
"step_count = 0 state = self.env.reset() while not done: state = np.reshape(state, (1,self.obs))",
"(a final state would've been the one after which simulation ended) non_final_mask =",
"nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections",
"x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)),",
"self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a",
"display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e =",
"= convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x):",
"= F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64,",
"states = np.vstack([x[0] for x in minibatch]) actions = np.array([x[1] for x in",
"self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state step_count",
"\"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train() print('Complete') env.render()",
"kernel_size = 5, stride = 2): return (size - (kernel_size - 1) -",
"= 16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation =",
"self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32,",
"range(num_episodes): # Initialize the environment and state env.reset() last_screen = get_screen() current_screen =",
"- 1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh =",
"discount=0.99, batch_size = 64, max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\",",
"return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed",
"IPython import display plt.ion() # if gpu is to be used device =",
"memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts",
"_ = env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new state last_screen =",
"y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: #",
"# (a final state would've been the one after which simulation ended) non_final_mask",
"durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit",
"https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array of Transitions # to Transition",
"math import random import numpy as np import matplotlib import matplotlib.pyplot as plt",
"that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory()",
"episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count = 0 state",
"random import numpy as np import matplotlib import matplotlib.pyplot as plt from collections",
"= Transition(*zip(*transitions)) # Compute a mask of non-final states and concatenate the batch",
"i_episode in range(num_episodes): # Initialize the environment and state env.reset() last_screen = get_screen()",
"display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1)",
"np # from collections import deque import random import gym # from typing",
"= random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch]) actions = np.array([x[1]",
"= torch.tensor([reward], device=device) # Observe new state last_screen = current_screen current_screen = get_screen()",
"= current_screen current_screen = get_screen() if not done: next_state = current_screen - last_screen",
"of Transitions # to Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a",
"torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F",
"0: # self.target_Qnet state = next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count))",
"Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for",
"the environment and state env.reset() last_screen = get_screen() current_screen = get_screen() state =",
"action action = select_action(state) _, reward, done, _ = env.step(action.item()) reward = torch.tensor([reward],",
"= self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16,",
"so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer =",
"matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion()",
"{} steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation",
"= np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if done: reward = -1",
"random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory) class Network(object):",
"if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see",
"'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position",
"one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,",
"stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32)",
"return model def train(self): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) #",
"DISCOUNT_RATE) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize",
"nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)",
"len(self.memory) class Network(object): def __init__(self, h, w, outputs): self.convNet = self.convNet(h, w, outputs)",
"batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn = self.build()",
"= False step_count = 0 state = self.env.reset() while not done: state =",
"done = False step_count = 0 state = self.env.reset() while not done: state",
"self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...')",
"reward) # Move to the next state state = next_state optimize_model() if done:",
"state = np.reshape(state, (1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample() else: action",
"actions = np.array([x[1] for x in minibatch]) rewards = np.array([x[2] for x in",
"convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x",
"of conv2d layers # and therefore the input image size, so compute it.",
"is to be used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition =",
"been the one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is",
"e = 1/.((episode/10)+1) done = False step_count = 0 state = self.env.reset() while",
"= 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action =",
"+ reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the",
"x in minibatch]) next_states = np.vstack([x[3] for x in minibatch]) Q_target = rewards",
"def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] =",
"> self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch])",
"self.convNet = self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16,",
"= Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr = 0.001):",
"and perform an action action = select_action(state) _, reward, done, _ = env.step(action.item())",
"Input, Dense, Reshape, Flatten, Dropout, Activation from keras import regularizers from keras.models import",
"n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float)",
"plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too if len(durations_t) >=",
"import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T env",
"self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build()",
"a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self):",
"keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation from keras import regularizers from",
"optim import torch.nn.functional as F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped #",
"len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size):",
"\"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity",
"return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory) class",
"= 64, max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size=",
"collections import namedtuple from itertools import count from PIL import Image import torch",
"next_state, reward) # Move to the next state state = next_state optimize_model() if",
"size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return",
"* 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x",
"= self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5,",
"F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def",
"= next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import Input,",
"step_count)) from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation from keras import",
"random import gym # from typing import List import argparse class DQN(): def",
"self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer",
"for # detailed explanation). This converts batch-array of Transitions # to Transition of",
"random batch of transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length",
"def train(self): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the",
"= target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE)",
"5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(),",
"= 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet",
"optimizer.step() num_episodes = 50 for i_episode in range(num_episodes): # Initialize the environment and",
"# set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython",
"= 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n",
"__init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self,",
"= \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def",
"= 5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet =",
"in minibatch]) rewards = np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3] for",
"current_screen - last_screen for t in count(): # Select and perform an action",
"args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train() print('Complete') env.render() env.close() plt.ioff()",
"keras.optimizers import Adam import numpy as np # from collections import deque import",
"(1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state,",
"num_episodes = 50 for i_episode in range(num_episodes): # Initialize the environment and state",
"from typing import List import argparse class DQN(): def __init__(self, discount=0.99, batch_size =",
"self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss",
"x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self,",
"loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr = 0.001): state =",
"import torch.nn.functional as F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set",
"therefore the input image size, so compute it. def conv2d_size_out(size, kernel_size = 5,",
"target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\",",
"Dropout, Activation from keras import regularizers from keras.models import Model from keras.optimizers import",
"self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END",
"means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots",
"= self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY =",
"for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count = 0",
"= Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action)",
"F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99,",
"T env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend()",
"memory.push(state, action, next_state, reward) # Move to the next state state = next_state",
"Transitions # to Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask",
"param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode in range(num_episodes):",
"1) plot_durations() break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ ==",
"param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode in range(num_episodes): # Initialize the",
"= torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s",
"next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber loss loss =",
"averages and plot them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100,",
"# self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state",
"= np.reshape(state, (1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample() else: action =",
"torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values =",
"import gym # from typing import List import argparse class DQN(): def __init__(self,",
"e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info =",
"next_state, reward, done, info = self.env.step(action) if done: reward = -1 buffer.push((state, action,",
"action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def train(self): if",
"50 for i_episode in range(num_episodes): # Initialize the environment and state env.reset() last_screen",
"= nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input",
"the expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch # Compute",
"self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random",
"self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration')",
"max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size",
"if np.random.rand() < e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward,",
"next state state = next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations() break",
"class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0]",
"non_final_next_states = torch.cat([s for s in batch.next_state if s is not None]) state_batch",
"perform an action action = select_action(state) _, reward, done, _ = env.step(action.item()) reward",
"outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3,",
"200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf()",
"kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def train(self): if len(memory) < BATCH_SIZE:",
"s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s",
"optimize_model() if done: episode_durations.append(t + 1) plot_durations() break if i_episode % TARGET_UPDATE ==",
"self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size",
"self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1",
"of replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h, w, outputs): self.convNet",
"so compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size",
"self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE",
"minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch]) actions =",
"Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity =",
"next_states = np.vstack([x[3] for x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1)",
"0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\",",
"plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100",
"nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T",
"if done: episode_durations.append(t + 1) plot_durations() break if i_episode % TARGET_UPDATE == 0:",
"Observe new state last_screen = current_screen current_screen = get_screen() if not done: next_state",
"= (next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values,",
"axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count %",
"the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array of Transitions",
"a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity",
"import List import argparse class DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes",
"= 2): return (size - (kernel_size - 1) - 1) // stride +",
"non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states =",
"= torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots are",
"\"\"\"Return length of replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h, w,",
"action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q",
"+ 1) plot_durations() break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__",
"Image import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional",
"Model(state, action) return model def train(self): if len(memory) < BATCH_SIZE: return transitions =",
"import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython =",
"if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False)",
"# from collections import deque import random import gym # from typing import",
"for t in count(): # Select and perform an action action = select_action(state)",
"from keras.optimizers import Adam import numpy as np # from collections import deque",
"= Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def train(self): if len(memory)",
"self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes",
"get_screen() if not done: next_state = current_screen - last_screen else: next_state = None",
"plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too if len(durations_t)",
"state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1)",
"* convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x =",
"reward, done, info = self.env.step(action) if done: reward = -1 buffer.push((state, action, reward,",
"the input image size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride",
"- 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size",
"argparse class DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes = 300): self.env",
"itertools import count from PIL import Image import torch import torch.nn as nn",
"states and concatenate the batch elements # (a final state would've been the",
"reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model",
"np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple from itertools",
"= (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch of transitions for training\"\"\"",
"Transition(*zip(*transitions)) # Compute a mask of non-final states and concatenate the batch elements",
"durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages",
"in count(): # Select and perform an action action = select_action(state) _, reward,",
"self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t",
"Number of Linear input connections depends on output of conv2d layers # and",
"plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for",
"nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32,",
"loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode",
"= F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env",
"next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for",
"self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions)",
"300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount",
"= -1 buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer,",
"# Move to the next state state = next_state optimize_model() if done: episode_durations.append(t",
"would've been the one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s",
"torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() #",
"device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state if s is not",
"16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state)",
"# Take 100 episode averages and plot them too if len(durations_t) >= 100:",
"as T env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline' in",
"= self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self,",
"self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs",
"state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch)",
"= nn.BatchNorm2d(32) # Number of Linear input connections depends on output of conv2d",
"if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self,",
"= np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3] for x in minibatch])",
"keras.models import Model from keras.optimizers import Adam import numpy as np # from",
"(self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch of transitions for training\"\"\" return",
"% self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state step_count +=1 print(\"Episode: {}",
"# Compute a mask of non-final states and concatenate the batch elements #",
"import regularizers from keras.models import Model from keras.optimizers import Adam import numpy as",
"discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE =",
"in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() # if gpu is",
"push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args)",
"stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends on output",
"Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array of",
"batch = Transition(*zip(*transitions)) # Compute a mask of non-final states and concatenate the",
"else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if done: reward",
"= capacity self.memory = [] self.position = 0 def push(self, *args): \"\"\"Saves a",
"lr = 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action",
"import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import",
"np.vstack([x[3] for x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y =",
"Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute",
"Q values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber loss",
"'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() # if gpu",
"Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward()",
"of transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay",
"for x in minibatch]) next_states = np.vstack([x[3] for x in minibatch]) Q_target =",
"torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots are updated",
"conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head =",
"_, reward, done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new",
"self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations():",
"next_state = current_screen - last_screen else: next_state = None memory.push(state, action, next_state, reward)",
"List import argparse class DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes =",
"required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]),",
"\"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def train(self):",
"len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043",
"0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def",
"if s is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch =",
"t in count(): # Select and perform an action action = select_action(state) _,",
"set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import",
"class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position =",
"torch.nn.functional as F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set up",
"Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return",
"batch_size = 64, max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True)",
"max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size=",
"gym import math import random import numpy as np import matplotlib import matplotlib.pyplot",
"h_size = 16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation",
"model = Model(state, action) return model def train(self): if len(memory) < BATCH_SIZE: return",
"import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as",
"done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new state last_screen",
"+ 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh",
"gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate",
"gpu is to be used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition",
"import count from PIL import Image import torch import torch.nn as nn import",
"discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END = 0.05",
"DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes = 300): self.env = gym.make('CartPole-v0')",
"torch.cat([s for s in batch.next_state if s is not None]) state_batch = torch.cat(batch.state)",
"episode_durations.append(t + 1) plot_durations() break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if",
"reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0]",
"Take 100 episode averages and plot them too if len(durations_t) >= 100: means",
"(see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array of Transitions # to",
"= max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\")",
"*args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position",
"minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] =",
"in minibatch]) next_states = np.vstack([x[3] for x in minibatch]) Q_target = rewards +",
"input image size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride =",
"nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)",
"last_screen = get_screen() current_screen = get_screen() state = current_screen - last_screen for t",
"mask of non-final states and concatenate the batch elements # (a final state",
"while not done: state = np.reshape(state, (1,self.obs)) if np.random.rand() < e: action =",
"Model from keras.optimizers import Adam import numpy as np # from collections import",
"loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for param",
"env.reset() last_screen = get_screen() current_screen = get_screen() state = current_screen - last_screen for",
"is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state",
"torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self,",
"5, stride = 2): return (size - (kernel_size - 1) - 1) //",
"= torch.cat([s for s in batch.next_state if s is not None]) state_batch =",
"conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) def",
"1) optimizer.step() num_episodes = 50 for i_episode in range(num_episodes): # Initialize the environment",
"display plt.ion() # if gpu is to be used device = torch.device(\"cuda\" if",
"of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask of non-final states and",
"0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet =",
"* DISCOUNT_RATE) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) #",
"# Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step()",
"Initialize the environment and state env.reset() last_screen = get_screen() current_screen = get_screen() state",
"stride = 2): return (size - (kernel_size - 1) - 1) // stride",
"self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x)))",
"= 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions)",
"= self.env.reset() while not done: state = np.reshape(state, (1,self.obs)) if np.random.rand() < e:",
"for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\" return",
"self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0:",
"0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size,",
"32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends",
"numpy as np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple",
"\"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn =",
"This converts batch-array of Transitions # to Transition of batch-arrays. batch = Transition(*zip(*transitions))",
"= nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5,",
"as F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set up matplotlib",
"state last_screen = current_screen current_screen = get_screen() if not done: next_state = current_screen",
"and concatenate the batch elements # (a final state would've been the one",
"1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh *",
"100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so",
"concatenate the batch elements # (a final state would've been the one after",
"state = next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations() break if i_episode",
"compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size -",
"= get_screen() current_screen = get_screen() state = current_screen - last_screen for t in",
"print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape, Flatten, Dropout,",
"Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target",
"last_screen for t in count(): # Select and perform an action action =",
"plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode",
"are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode",
"== \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\",",
"5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs,",
"2): return (size - (kernel_size - 1) - 1) // stride + 1",
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward'))",
"not done: state = np.reshape(state, (1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample()",
"import matplotlib import matplotlib.pyplot as plt from collections import namedtuple from itertools import",
"np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3] for x in minibatch]) Q_target",
"class DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes = 300): self.env =",
"= Model(state, action) return model def train(self): if len(memory) < BATCH_SIZE: return transitions",
"= next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations() break if i_episode %",
"== 0: # self.target_Qnet state = next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode,",
"self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY =",
"self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs,",
"64, max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0]",
"after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)),",
"directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5",
"from collections import namedtuple from itertools import count from PIL import Image import",
"x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class",
"= argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args =",
"them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means =",
"reward = -1 buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch =",
"None memory.push(state, action, next_state, reward) # Move to the next state state =",
"next_state = None memory.push(state, action, next_state, reward) # Move to the next state",
"None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1,",
"np.reshape(state, (1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state))",
"a mask of non-final states and concatenate the batch elements # (a final",
"action = select_action(state) _, reward, done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device)",
"batch of transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of",
"__init__(self, discount=0.99, batch_size = 64, max_episodes = 300): self.env = gym.make('CartPole-v0') # self.env.wrappers.Monitor(env,",
"break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap",
"# if gpu is to be used device = torch.device(\"cuda\" if torch.cuda.is_available() else",
"torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object):",
"ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0",
"info = self.env.step(action) if done: reward = -1 buffer.push((state, action, reward, next_state)) if",
"plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots are updated if is_ipython:",
"target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE) +",
"import matplotlib.pyplot as plt from collections import namedtuple from itertools import count from",
"plot_durations() break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\":",
"= Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state",
"y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY",
"expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch # Compute Huber",
"not done: next_state = current_screen - last_screen else: next_state = None memory.push(state, action,",
"state = current_screen - last_screen for t in count(): # Select and perform",
"import namedtuple from itertools import count from PIL import Image import torch import",
"self.env.step(action) if done: reward = -1 buffer.push((state, action, reward, next_state)) if len(buffer) >",
"matplotlib.pyplot as plt from collections import namedtuple from itertools import count from PIL",
"for x in minibatch]) actions = np.array([x[1] for x in minibatch]) rewards =",
"torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline'",
"regularizers from keras.models import Model from keras.optimizers import Adam import numpy as np",
"batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array of Transitions #",
"h, w, outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1",
"= memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This",
"environment and state env.reset() last_screen = get_screen() current_screen = get_screen() state = current_screen",
"1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h)))",
"stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw *",
"= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class",
"and plot them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1)",
"required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train()",
"is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value",
"length of replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h, w, outputs):",
"Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model def train(self): if len(memory) <",
"action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action)",
"done: state = np.reshape(state, (1,self.obs)) if np.random.rand() < e: action = self.env.action_space.sample() else:",
"from keras import regularizers from keras.models import Model from keras.optimizers import Adam import",
"is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e",
"import Adam import numpy as np # from collections import deque import random",
"collections import deque import random import gym # from typing import List import",
"replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h, w, outputs): self.convNet =",
"+=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape, Flatten,",
"to be used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state',",
"F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env =",
"self.convNet(h, w, outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)",
"= torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and",
"self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch]) actions = np.array([x[1] for x",
"def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return",
"linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self,",
"\"\"\"Select a random batch of transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self):",
"in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions]",
"from itertools import count from PIL import Image import torch import torch.nn as",
"reward = torch.tensor([reward], device=device) # Observe new state last_screen = current_screen current_screen =",
"= nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 =",
"Adam import numpy as np # from collections import deque import random import",
"batch_size): \"\"\"Select a random batch of transitions for training\"\"\" return random.sample(self.memory, batch_size) def",
"(kernel_size - 1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh",
"step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape,",
"gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size",
"= np.vstack([x[0] for x in minibatch]) actions = np.array([x[1] for x in minibatch])",
"buffer = ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False",
"= conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs)",
"max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights())",
"# and therefore the input image size, so compute it. def conv2d_size_out(size, kernel_size",
"ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]),",
"be used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action',",
"device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values = (next_state_values",
"model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50",
"stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32)",
"not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state if",
"gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from",
"= Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch of",
"action, next_state, reward) # Move to the next state state = next_state optimize_model()",
"class Network(object): def __init__(self, h, w, outputs): self.convNet = self.convNet(h, w, outputs) def",
"to Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask of non-final",
"kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 =",
"convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32",
"means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause",
"minibatch]) actions = np.array([x[1] for x in minibatch]) rewards = np.array([x[2] for x",
"from keras.models import Model from keras.optimizers import Adam import numpy as np #",
"count from PIL import Image import torch import torch.nn as nn import torch.optim",
"None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state if s",
"current_screen - last_screen else: next_state = None memory.push(state, action, next_state, reward) # Move",
"np.vstack([x[0] for x in minibatch]) actions = np.array([x[1] for x in minibatch]) rewards",
"get_screen() current_screen = get_screen() state = current_screen - last_screen for t in count():",
"Reshape, Flatten, Dropout, Activation from keras import regularizers from keras.models import Model from",
"depends on output of conv2d layers # and therefore the input image size,",
"if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode in range(self.MAX_EPISODES):",
"plt.pause(0.001) # pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True)",
"minibatch]) next_states = np.vstack([x[3] for x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states),",
"s in batch.next_state if s is not None]) state_batch = torch.cat(batch.state) action_batch =",
"self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations,",
"= self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if",
"as np # from collections import deque import random import gym # from",
"= 0 state = self.env.reset() while not done: state = np.reshape(state, (1,self.obs)) if",
"next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values",
"self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if done:",
"= 200 self.main_Qnet = self.Network(obs, n_actions) self.target_Qnet = self.Network(obs, n_actions) def plot_durations(): plt.figure(2)",
"deque import random import gym # from typing import List import argparse class",
"# to Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask of",
"plt from collections import namedtuple from itertools import count from PIL import Image",
"Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch of transitions",
"nn.BatchNorm2d(32) # Number of Linear input connections depends on output of conv2d layers",
"16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2",
"= 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() # if",
"minibatch]) rewards = np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3] for x",
"= gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE =",
"dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state if s is not None])",
"done: episode_durations.append(t + 1) plot_durations() break if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict())",
"= max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY =",
"self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn",
"self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn",
"ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states",
"- last_screen for t in count(): # Select and perform an action action",
"= np.array([x[1] for x in minibatch]) rewards = np.array([x[2] for x in minibatch])",
"batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in batch.next_state if s is",
"self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch",
"def __len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self,",
"= torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device)",
"-1 buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE)",
"up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display",
"return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0')",
"self.position = 0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity:",
"def build(self, h_size = 16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1 =",
"BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for #",
"used device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state',",
"forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0),",
"ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count =",
"ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args",
"1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size =",
"steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation from",
"= F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object):",
"ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train() print('Complete')",
"Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state =",
"Compute a mask of non-final states and concatenate the batch elements # (a",
"batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE",
"= ReplayMemory() for episode in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count",
"keras import regularizers from keras.models import Model from keras.optimizers import Adam import numpy",
"env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new state last_screen = current_screen current_screen",
"= 50 for i_episode in range(num_episodes): # Initialize the environment and state env.reset()",
"= batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START =",
"= 5, stride = 2): return (size - (kernel_size - 1) - 1)",
"= main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the",
"in range(self.MAX_EPISODES): e = 1/.((episode/10)+1) done = False step_count = 0 state =",
"for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode in",
"import numpy as np import matplotlib import matplotlib.pyplot as plt from collections import",
"plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too",
"np.array([x[1] for x in minibatch]) rewards = np.array([x[2] for x in minibatch]) next_states",
"memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h, w, outputs): self.convNet = self.convNet(h,",
"= self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY ==",
"for x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states)",
"build(self, h_size = 16, lr = 0.001): state = Input(shape=(self.input_size,)) dense1 = Dense(h_size,",
"env = gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if",
"# Compute the expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch",
"on output of conv2d layers # and therefore the input image size, so",
"numpy as np # from collections import deque import random import gym #",
"an action action = select_action(state) _, reward, done, _ = env.step(action.item()) reward =",
"// stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw",
"= vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train() print('Complete') env.render() env.close() plt.ioff() plt.show()",
"if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state step_count +=1",
"transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation).",
"return len(self.memory) class Network(object): def __init__(self, h, w, outputs): self.convNet = self.convNet(h, w,",
"__init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n",
"non-final states and concatenate the batch elements # (a final state would've been",
"policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode in range(num_episodes): # Initialize",
"self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends on output of",
"namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory",
"if done: reward = -1 buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE:",
"torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values =",
"if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap =",
"= env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new state last_screen = current_screen",
"= batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn =",
"= self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES =",
"matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() # if gpu is to",
"in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes = 50 for i_episode in range(num_episodes): #",
"< e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info",
"self.target_Qnet state = next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers",
"Activation from keras import regularizers from keras.models import Model from keras.optimizers import Adam",
"get_screen() state = current_screen - last_screen for t in count(): # Select and",
"import display plt.ion() # if gpu is to be used device = torch.device(\"cuda\"",
"def sample(self, batch_size): \"\"\"Select a random batch of transitions for training\"\"\" return random.sample(self.memory,",
"= nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x",
"self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE",
"w, outputs) def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1",
"# Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad()",
"current_screen current_screen = get_screen() if not done: next_state = current_screen - last_screen else:",
"Flatten, Dropout, Activation from keras import regularizers from keras.models import Model from keras.optimizers",
"# Number of Linear input connections depends on output of conv2d layers #",
"x in minibatch]) actions = np.array([x[1] for x in minibatch]) rewards = np.array([x[2]",
"F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1,",
"count(): # Select and perform an action action = select_action(state) _, reward, done,",
"as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as",
"=\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr = 0.001): state = Input(shape=(self.input_size,))",
"dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them",
"'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory =",
"if is_ipython: from IPython import display plt.ion() # if gpu is to be",
"np.random.rand() < e: action = self.env.action_space.sample() else: action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done,",
"current_screen = get_screen() state = current_screen - last_screen for t in count(): #",
"self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in minibatch]) actions",
"convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2",
"next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values = (next_state_values *",
"= torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected Q values next_Q_values",
"= Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model",
"sample(self, batch_size): \"\"\"Select a random batch of transitions for training\"\"\" return random.sample(self.memory, batch_size)",
"batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory) class Network(object): def",
"final state would've been the one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda",
"= F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters():",
"= get_screen() if not done: next_state = current_screen - last_screen else: next_state =",
"of non-final states and concatenate the batch elements # (a final state would've",
"and therefore the input image size, so compute it. def conv2d_size_out(size, kernel_size =",
"max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200",
"= gym.make('CartPole-v0') # self.env.wrappers.Monitor(env, directory=\"results/\", force=True) self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE =",
"action) return model def train(self): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE)",
"s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for s in",
"self.build() self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr",
"s is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward)",
"from PIL import Image import torch import torch.nn as nn import torch.optim as",
"in batch.next_state if s is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action)",
"[] self.position = 0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) <",
"actions] = Q_target # self.main_Qnet.train_on if step_count % self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet",
"= torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values",
"self.obs = self.env.observation_space.shape[0] self.n_actions = self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES",
"current_screen = get_screen() if not done: next_state = current_screen - last_screen else: next_state",
"Network(object): def __init__(self, h, w, outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h,",
"action = np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if done: reward =",
"main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() # Compute the expected",
"outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16,",
"in minibatch]) actions = np.array([x[1] for x in minibatch]) rewards = np.array([x[2] for",
"a random batch of transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return",
"def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size - (kernel_size -",
"len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy())",
"the one after which simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not",
"required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"])) dqn.train() print('Complete') env.render() env.close()",
"self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) #",
"next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations() break if i_episode % TARGET_UPDATE",
"= None memory.push(state, action, next_state, reward) # Move to the next state state",
"connections depends on output of conv2d layers # and therefore the input image",
"= get_screen() state = current_screen - last_screen for t in count(): # Select",
"self.env.reset() while not done: state = np.reshape(state, (1,self.obs)) if np.random.rand() < e: action",
"self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END = 0.05 self.EPS_DECAY = 200 self.main_Qnet",
"model def train(self): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose",
"def convNet(h, w, outputs): self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16)",
"100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) #",
"self.main_dqn.compile(optimizer = Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr =",
"1/.((episode/10)+1) done = False step_count = 0 state = self.env.reset() while not done:",
"x in minibatch]) rewards = np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3]",
"= select_action(state) _, reward, done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device) #",
"is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() #",
"import Model from keras.optimizers import Adam import numpy as np # from collections",
"loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for param in",
"import math import random import numpy as np import matplotlib import matplotlib.pyplot as",
"capacity self.memory = [] self.position = 0 def push(self, *args): \"\"\"Saves a transition.\"\"\"",
"np.argmax(self.main_Qnet.predict(state)) next_state, reward, done, info = self.env.step(action) if done: reward = -1 buffer.push((state,",
"the batch elements # (a final state would've been the one after which",
"__name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\",",
"and state env.reset() last_screen = get_screen() current_screen = get_screen() state = current_screen -",
"if not done: next_state = current_screen - last_screen else: next_state = None memory.push(state,",
"transitions for training\"\"\" return random.sample(self.memory, batch_size) def __len__(self): \"\"\"Return length of replay memory\"\"\"",
"self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select a random batch of transitions for",
"= self.Network(obs, n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode')",
"argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args())",
"plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too if",
"image size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2):",
"import random import numpy as np import matplotlib import matplotlib.pyplot as plt from",
"= namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity",
"if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means))",
"reward, done, _ = env.step(action.item()) reward = torch.tensor([reward], device=device) # Observe new state",
"conv2d_size_out(size, kernel_size = 5, stride = 2): return (size - (kernel_size - 1)",
"- last_screen else: next_state = None memory.push(state, action, next_state, reward) # Move to",
"from IPython import display plt.ion() # if gpu is to be used device",
"32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3",
"pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def",
"done, info = self.env.step(action) if done: reward = -1 buffer.push((state, action, reward, next_state))",
"rewards = np.array([x[2] for x in minibatch]) next_states = np.vstack([x[3] for x in",
"updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer = ReplayMemory() for episode in",
"def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions =",
"\"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position =",
"ap.add_argument(\"-b\", \"--batch\", required=False) ap.add_argument(\"-d\", \"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn",
"torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot",
"Move to the next state state = next_state optimize_model() if done: episode_durations.append(t +",
"transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def",
"train(self): if len(memory) < BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch",
"Linear input connections depends on output of conv2d layers # and therefore the",
"episode averages and plot them too if len(durations_t) >= 100: means = durations_t.unfold(0,",
"kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends on",
"means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots are updated if",
"# Observe new state last_screen = current_screen current_screen = get_screen() if not done:",
"done: next_state = current_screen - last_screen else: next_state = None memory.push(state, action, next_state,",
"outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x)))",
"namedtuple from itertools import count from PIL import Image import torch import torch.nn",
"last_screen = current_screen current_screen = get_screen() if not done: next_state = current_screen -",
"1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that",
"-1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs =",
"# pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf())",
"= torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()",
"+ self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if",
"(size - (kernel_size - 1) - 1) // stride + 1 convw =",
"__init__(self, h, w, outputs): self.convNet = self.convNet(h, w, outputs) def convNet(h, w, outputs):",
"__len__(self): \"\"\"Return length of replay memory\"\"\" return len(self.memory) class Network(object): def __init__(self, h,",
"'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = []",
"state = self.env.reset() while not done: state = np.reshape(state, (1,self.obs)) if np.random.rand() <",
"else: next_state = None memory.push(state, action, next_state, reward) # Move to the next",
"torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms",
"the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1) optimizer.step() num_episodes =",
"the next state state = next_state optimize_model() if done: episode_durations.append(t + 1) plot_durations()",
"action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE,",
"x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300):",
"n_actions) def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy())",
"output of conv2d layers # and therefore the input image size, so compute",
"= discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START = 0.9 self.EPS_END =",
"# from typing import List import argparse class DQN(): def __init__(self, discount=0.99, batch_size",
"state = next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import",
"of Linear input connections depends on output of conv2d layers # and therefore",
"reward_batch = torch.cat(batch.reward) Q_value = main_Qnet(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] =",
"\"--discount\", required=False) ap.add_argument(\"-ep\", \"--max\", required=False) args = vars(ap.parse_args()) dqn = DQN(int(args[\"batch\"]), float(args[\"discount\"]), int(args[\"max\"]))",
"converts batch-array of Transitions # to Transition of batch-arrays. batch = Transition(*zip(*transitions)) #",
"activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state, action) return model",
"i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser()",
"= 0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory) < self.capacity: self.memory.append(None)",
"as np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple from",
"# Select and perform an action action = select_action(state) _, reward, done, _",
"self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES = max_episodes self.main_dqn =",
"Compute the expected Q values next_Q_values = (next_state_values * DISCOUNT_RATE) + reward_batch #",
"= np.vstack([x[3] for x in minibatch]) Q_target = rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y",
"return (size - (kernel_size - 1) - 1) // stride + 1 convw",
"== 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\", \"--batch\", required=False)",
"conv2d layers # and therefore the input image size, so compute it. def",
"# Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for # detailed explanation). This converts batch-array",
"= current_screen - last_screen else: next_state = None memory.push(state, action, next_state, reward) #",
"for x in minibatch]) rewards = np.array([x[2] for x in minibatch]) next_states =",
"batch-array of Transitions # to Transition of batch-arrays. batch = Transition(*zip(*transitions)) # Compute",
"len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x in",
"= [] self.position = 0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if len(self.memory)",
"dense1 = Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model = Model(state,",
"self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3",
"import gym import math import random import numpy as np import matplotlib import",
"if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states = np.vstack([x[0] for x",
"is_ipython: from IPython import display plt.ion() # if gpu is to be used",
"to the next state state = next_state optimize_model() if done: episode_durations.append(t + 1)",
"matplotlib import matplotlib.pyplot as plt from collections import namedtuple from itertools import count",
"import random import gym # from typing import List import argparse class DQN():",
"self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target # self.main_Qnet.train_on if step_count",
"as optim import torch.nn.functional as F import torchvision.transforms as T env = gym.make('CartPole-v0').unwrapped",
"done: reward = -1 buffer.push((state, action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch",
"= conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head",
"import deque import random import gym # from typing import List import argparse",
"= 5 self.MAX_EPISODES = max_episodes self.main_dqn = self.build() self.target_dqn = self.build() self.main_dqn.compile(optimizer =",
"expected_state_action_values.unsqueeze(1)) # Optimize the model optimizer.zero_grad() loss.backward() for param in policy_net.parameters(): param.grad.data.clamp_(-1, 1)",
"import argparse class DQN(): def __init__(self, discount=0.99, batch_size = 64, max_episodes = 300):",
"Input(shape=(self.input_size,)) dense1 = Dense(h_size, activation = \"relu\")(state) action = Dense(self.output_size, kernel_regularizer=regularizers.l2(0.01))(dense1) model =",
"DQN(object): def __init__(self, batch_size=64, discount_rate=0.99, max_episodes=300): self.env = gym.make('CartPole-v0') self.obs = self.env.observation_space.shape[0] self.n_actions",
"batch.next_state if s is not None]) state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch",
"state env.reset() last_screen = get_screen() current_screen = get_screen() state = current_screen - last_screen",
"= current_screen - last_screen for t in count(): # Select and perform an",
"self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear",
"self.memory = [] self.position = 0 def push(self, *args): \"\"\"Saves a transition.\"\"\" if",
"= gym.make('CartPole-v0').unwrapped # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython:",
"batch elements # (a final state would've been the one after which simulation",
"action, reward, next_state)) if len(buffer) > self.BATCH_SIZE: minibatch = random.sample(buffer, self.BATCH_SIZE) states =",
"simulation ended) non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8)",
"< self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position+1)%self.capacity def sample(self, batch_size): \"\"\"Select",
"- (kernel_size - 1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w)))",
"nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of",
"import Image import torch import torch.nn as nn import torch.optim as optim import",
"else \"cpu\") Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity):",
"torch.tensor([reward], device=device) # Observe new state last_screen = current_screen current_screen = get_screen() if",
"torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) non_final_next_states = torch.cat([s for",
"< BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for",
"False step_count = 0 state = self.env.reset() while not done: state = np.reshape(state,",
"too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99),",
"self.TARGET_UPDAT_FREQUENCY == 0: # self.target_Qnet state = next_state step_count +=1 print(\"Episode: {} steps:",
"self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5 self.EPS_START",
"next_state step_count +=1 print(\"Episode: {} steps: {}\".format(episode, step_count)) from keras.layers import Input, Dense,",
"self.input_size= self.env.observation_space.shape[0] self.output_size= self.env.action_space.n self.DISCOUNT_RATE=discount self.BATCH_SIZE = batch_size self.TARGET_UPDATE_FREQUENCY = 5 self.MAX_EPISODES =",
"batch-arrays. batch = Transition(*zip(*transitions)) # Compute a mask of non-final states and concatenate",
"Adam(), loss =\"mean_squared_error\") self.target_dqn.set_weights(self.main_dqn.get_weights()) def build(self, h_size = 16, lr = 0.001): state",
"self.env.action_space.n self.BATCH_SIZE = batch_size self.DISCOUNT_RATE = discount_rate self.MAX_EPISODES = max_episodes self.TARGET_UPDAT_FREQUENCY = 5",
"% TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) if __name__ == \"__main__\": ap = argparse.ArgumentParser() ap.add_argument(\"-b\",",
"= rewards + self.DISCOUNT_RATE+np.max(self.target_Qnet.forward(next_states), axis=1) y = self.main_Qnet(states) y[np.arrange(len(states)), actions] = Q_target #",
"100 episode averages and plot them too if len(durations_t) >= 100: means =",
"bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) def train(self): buffer",
"plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take",
"convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size,",
"= nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number"
] |
[
"if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def",
">>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction,",
"key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones to transpose >>>",
"B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result = '' try:",
"tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index =",
"on target key. >>> transpose_line('| A | A# | Bb | C#m7/F# |',",
"('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#':",
"not source_chords or not source_line: return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord)",
"key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if source_key in key_names:",
"a key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E",
"for example F# instead of Gb. >>> transpose_line('| Gb |', 0, 'Gb') '|",
"\\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction,",
"in options: if option in ('-f', '--from'): from_key = value elif option in",
"% source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at the given internal index.",
"start, jazzy ending\\\\n| E | A B | Cm7#11/D# |\\\\n' \"\"\" direction =",
"options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err),",
"return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords,",
"depends on the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index",
"= re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of a key >>> get_index_from_key('Bb')",
">>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index",
"'A | Bb |' \"\"\" if source_line[0] != '|': return source_line source_chords =",
"arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" %",
"return target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a",
"common key if sharp/flat, for example F# instead of Gb. >>> transpose_line('| Gb",
"def usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def",
"'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b',",
"= 'C' to_key = 'C' file_name = None try: options, arguments = getopt.getopt(sys.argv[1:],",
"get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from",
"'#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b',",
"return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord)",
">>> transpose_line('A | Bb |', -2, 'C') 'A | Bb |' \"\"\" if",
"--to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key = 'C'",
"= '' try: for line in open(file_name): result += transpose_line(line, direction, to_key) return",
"+ \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord,",
"'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#':",
"= [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',),",
"get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index -",
"after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) +",
"return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the",
"== '--doctest': import doctest doctest.testmod() exit() else: usage() if arguments: file_name = arguments[0]",
"use the more common key if sharp/flat, for example F# instead of Gb.",
"usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number of keys if",
"1 \"\"\" for key_names in key_list: if source_key in key_names: return key_list.index(key_names) raise",
"A B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result = ''",
"'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of",
"file from a key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy",
"for line in open(file_name): result += transpose_line(line, direction, to_key) return result except IOError:",
"flat depends on the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names =",
"'Bb' \"\"\" key_names = key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat =",
"= key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat]",
"'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences",
"elif option == '--doctest': import doctest doctest.testmod() exit() else: usage() if arguments: file_name",
"'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#',",
"F# instead of Gb. >>> transpose_line('| Gb |', 0, 'Gb') '| F# |'",
"target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index",
"to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a",
"'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of a",
"|', 0, 'Gb') '| F# |' Lines not starting with pipe will not",
"len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key):",
">>> transpose_line('| Gb |', 0, 'Gb') '| F# |' Lines not starting with",
"source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a key to another.",
"('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',),",
"try: for line in open(file_name): result += transpose_line(line, direction, to_key) return result except",
"not starting with pipe will not be transposed >>> transpose_line('A | Bb |',",
"'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal",
"key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return",
"as err: print(str(err), usage(), sys.exit(2)) for option, value in options: if option in",
"get_transponation_steps(from_key, to_key) result = '' try: for line in open(file_name): result += transpose_line(line,",
"'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb':",
"transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key)",
"'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets",
"recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or not source_line: return source_line source_chord",
"example F# instead of Gb. >>> transpose_line('| Gb |', 0, 'Gb') '| F#",
"= sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of",
"main(): from_key = 'C' to_key = 'C' file_name = None try: options, arguments",
"'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C':",
"result = transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result)",
"of half tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key)",
"-> %s):\" % (from_key, to_key)) print(result) if __name__ == '__main__': print(transpose_line('|Eb', 2, 'C'))",
"from_key = 'C' to_key = 'C' file_name = None try: options, arguments =",
"'--to'): to_key = value elif option == '--doctest': import doctest doctest.testmod() exit() else:",
"= get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:' print() '%s",
"target_key): \"\"\"Gets the number of half tones to transpose >>> get_transponation_steps('D', 'C') -2",
"-2, 'C') '| G | Ab | Ab | Bm7/E |' Different keys",
"source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or not",
"on target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return",
"= source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction,",
"os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key = 'C' file_name = None",
"a pipe. Examples: >>> transpose_line('| A | A# | Bb | C#m7/F# |',",
"!= '|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def",
"= key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if",
"% len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0]",
"('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences =",
"it starts with a pipe. Examples: >>> transpose_line('| A | A# | Bb",
"| Bb |', -2, 'C') 'A | Bb |' \"\"\" if source_line[0] !=",
"|' Lines not starting with pipe will not be transposed >>> transpose_line('A |",
"a number of half tones. Sharp or flat depends on target key. >>>",
"('-f', '--from'): from_key = value elif option in ('-t', '--to'): to_key = value",
"to_key) print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result) if __name__ == '__main__':",
"index. Sharp or flat depends on the target key. >>> get_key_from_index(1, 'Eb') 'Bb'",
"'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex",
"be transposed >>> transpose_line('A | Bb |', -2, 'C') 'A | Bb |'",
"\"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name,",
"key. >>> transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'D')",
"key if sharp/flat, for example F# instead of Gb. >>> transpose_line('| Gb |',",
"def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number of keys if it",
"'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb':",
"'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#',",
"in open(file_name): result += transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid filename!\")",
"source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index,",
"from_key, to_key): \"\"\"Transposes a file from a key to another. >>> transpose_file('example.txt', 'D',",
"= getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2))",
"'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option, value in options:",
"transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'D') '| G",
"key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at the given",
"'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def",
"direction, to_key): if not source_chords or not source_line: return source_line source_chord = source_chords.pop(0)",
"('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b',",
"elif option in ('-t', '--to'): to_key = value elif option == '--doctest': import",
"| A# | Bb | C#m7/F# |', -2, 'D') '| G | G#",
"print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number of",
"the key at the given internal index. Sharp or flat depends on the",
"with a pipe. Examples: >>> transpose_line('| A | A# | Bb | C#m7/F#",
"the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)]",
">>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if source_key in key_names: return",
"source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def",
"to_key): if not source_chords or not source_line: return source_line source_chord = source_chords.pop(0) chord_index",
"sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number",
"source_chords, direction, to_key): if not source_chords or not source_line: return source_line source_chord =",
"direction, to_key) def usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__)",
"('-t', '--to'): to_key = value elif option == '--doctest': import doctest doctest.testmod() exit()",
"in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key):",
"'--doctest': import doctest doctest.testmod() exit() else: usage() if arguments: file_name = arguments[0] else:",
"will be sharp or flat depending on target key. >>> transpose_line('| A |",
"instead of Gb. >>> transpose_line('| Gb |', 0, 'Gb') '| F# |' Lines",
"of half tones. Sharp or flat depends on target key. >>> transpose('C', 3,",
"except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a",
"'Gb') '| F# |' Lines not starting with pipe will not be transposed",
"'C') 'A | Bb |' \"\"\" if source_line[0] != '|': return source_line source_chords",
"| G# | G# | Bm7/E |' It will use the more common",
"\"\"\"Gets the number of half tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\"",
"len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def",
"source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return",
"given internal index. Sharp or flat depends on the target key. >>> get_key_from_index(1,",
"| Bb |' \"\"\" if source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line)",
"def main(): from_key = 'C' to_key = 'C' file_name = None try: options,",
"= value elif option in ('-t', '--to'): to_key = value elif option ==",
"sys.exit(2)) for option, value in options: if option in ('-f', '--from'): from_key =",
"source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction,",
"key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)] if len(key_names)",
"G | G# | G# | Bm7/E |' It will use the more",
"Bb |' \"\"\" if source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line) return",
"Sharp or flat depends on target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\"",
"if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key,",
"doctest.testmod() exit() else: usage() if arguments: file_name = arguments[0] else: usage() result =",
"A# | Bb | C#m7/F# |', -2, 'C') '| G | Ab |",
"'%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key",
"'--from'): from_key = value elif option in ('-t', '--to'): to_key = value elif",
"Lines not starting with pipe will not be transposed >>> transpose_line('A | Bb",
"options: if option in ('-f', '--from'): from_key = value elif option in ('-t',",
"get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)] if len(key_names) > 1:",
"{ 'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b',",
"return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key)",
"file_name = None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except",
"for option, value in options: if option in ('-f', '--from'): from_key = value",
"to_key = 'C' file_name = None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=',",
"= value elif option == '--doctest': import doctest doctest.testmod() exit() else: usage() if",
"usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main():",
"if not source_chords or not source_line: return source_line source_chord = source_chords.pop(0) chord_index =",
"'C' file_name = None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest'])",
"a file from a key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start,",
"recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or",
"will not be transposed >>> transpose_line('A | Bb |', -2, 'C') 'A |",
"re, getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',),",
"'#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b',",
"|' Different keys will be sharp or flat depending on target key. >>>",
"('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b']",
"'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D':",
"= chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\",
"chord a number of half tones. Sharp or flat depends on target key.",
"+ len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords,",
"key at the given internal index. Sharp or flat depends on the target",
"= ['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb': 'b', 'B':",
"on the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index %",
"sharp or flat depending on target key. >>> transpose_line('| A | A# |",
"0, 'Gb') '| F# |' Lines not starting with pipe will not be",
"sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb': 'b',",
"G | Ab | Ab | Bm7/E |' Different keys will be sharp",
"'C') '| G | Ab | Ab | Bm7/E |' Different keys will",
"= transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result) if",
"pipe will not be transposed >>> transpose_line('A | Bb |', -2, 'C') 'A",
"def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones to transpose >>> get_transponation_steps('D',",
"if sharp/flat, for example F# instead of Gb. >>> transpose_line('| Gb |', 0,",
"half tones. Sharp or flat depends on target key. >>> transpose('C', 3, 'Bb')",
"key_list: if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key)",
"to_key) def usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2)",
"getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option, value in options: if option",
"'#', 'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the",
"'#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\")",
"'| G | G# | G# | Bm7/E |' It will use the",
"= None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError",
"sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half",
"| Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result = '' try: for",
"|', -2, 'D') '| G | G# | G# | Bm7/E |' It",
"starts with a pipe. Examples: >>> transpose_line('| A | A# | Bb |",
"print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C'",
"\"\"\"Gets the internal index of a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names",
"half tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index",
"result = '' try: for line in open(file_name): result += transpose_line(line, direction, to_key)",
"Bb |', -2, 'C') 'A | Bb |' \"\"\" if source_line[0] != '|':",
"print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result) if __name__ == '__main__': print(transpose_line('|Eb',",
"direction, to_key) return result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key):",
"chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:],",
"import os import re, getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',),",
"of a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if source_key",
"to_key): \"\"\"Transposes a line a number of keys if it starts with a",
"A | A# | Bb | C#m7/F# |', -2, 'C') '| G |",
"source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key):",
"option == '--doctest': import doctest doctest.testmod() exit() else: usage() if arguments: file_name =",
"value elif option in ('-t', '--to'): to_key = value elif option == '--doctest':",
"'E') 'Rocking start, jazzy ending\\\\n| E | A B | Cm7#11/D# |\\\\n' \"\"\"",
"'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#',",
"chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord,",
">>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)] if len(key_names) >",
"| Bm7/E |' It will use the more common key if sharp/flat, for",
"A# | Bb | C#m7/F# |', -2, 'D') '| G | G# |",
"sys.exit(2) def main(): from_key = 'C' to_key = 'C' file_name = None try:",
"| Ab | Bm7/E |' Different keys will be sharp or flat depending",
"a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if source_key in",
"in key_list: if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" %",
"return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones to transpose",
"'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db':",
"'#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#',",
"getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for",
"transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number of half tones. Sharp or",
"Bm7/E |' It will use the more common key if sharp/flat, for example",
"'D') '| G | G# | G# | Bm7/E |' It will use",
"|', -2, 'C') '| G | Ab | Ab | Bm7/E |' Different",
"get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename'",
"flat depending on target key. >>> transpose_line('| A | A# | Bb |",
"internal index. Sharp or flat depends on the target key. >>> get_key_from_index(1, 'Eb')",
"source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at the given internal index. Sharp",
"a number of keys if it starts with a pipe. Examples: >>> transpose_line('|",
"'| F# |' Lines not starting with pipe will not be transposed >>>",
"('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat",
"not source_line: return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index",
"'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage(): print()",
"--from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key =",
"import doctest doctest.testmod() exit() else: usage() if arguments: file_name = arguments[0] else: usage()",
"at the given internal index. Sharp or flat depends on the target key.",
"value elif option == '--doctest': import doctest doctest.testmod() exit() else: usage() if arguments:",
"A | A# | Bb | C#m7/F# |', -2, 'D') '| G |",
"'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b',",
"a line a number of keys if it starts with a pipe. Examples:",
"\"\"\"Gets the key at the given internal index. Sharp or flat depends on",
"for key_names in key_list: if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key:",
"option in ('-f', '--from'): from_key = value elif option in ('-t', '--to'): to_key",
"| C#m7/F# |', -2, 'D') '| G | G# | G# | Bm7/E",
"from_key, to_key) print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result) if __name__ ==",
"Examples: >>> transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'C')",
"key_names in key_list: if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\"",
"transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'C') '| G",
"'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex =",
"else: usage() if arguments: file_name = arguments[0] else: usage() result = transpose_file(file_name, from_key,",
"usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" % (from_key, to_key))",
"transpose_line('A | Bb |', -2, 'C') 'A | Bb |' \"\"\" if source_line[0]",
"arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(),",
"the number of half tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index",
"from_key = value elif option in ('-t', '--to'): to_key = value elif option",
"'| G | Ab | Ab | Bm7/E |' Different keys will be",
"'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat",
"to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E | A",
"if arguments: file_name = arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result",
"'Rocking start, jazzy ending\\\\n| E | A B | Cm7#11/D# |\\\\n' \"\"\" direction",
"\"\"\" if source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords,",
"key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of a key >>>",
"depends on target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord)",
"get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:' print() '%s --from=Eb",
"another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E | A B",
"Gb |', 0, 'Gb') '| F# |' Lines not starting with pipe will",
"or flat depends on target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index",
"transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction,",
">>> transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'C') '|",
"flat depends on target key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index =",
"+ \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord",
"key_names: return key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets",
"usage() if arguments: file_name = arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key)",
"value in options: if option in ('-f', '--from'): from_key = value elif option",
"open(file_name): result += transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid filename!\") usage()",
"Bb | C#m7/F# |', -2, 'C') '| G | Ab | Ab |",
"source_line: return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index +",
"source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key)",
"key_list.index(key_names) raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key",
"source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number of",
"% os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key = 'C' file_name =",
"(%s -> %s):\" % (from_key, to_key)) print(result) if __name__ == '__main__': print(transpose_line('|Eb', 2,",
"or flat depending on target key. >>> transpose_line('| A | A# | Bb",
"result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line",
"key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not",
"return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords",
"| G# | Bm7/E |' It will use the more common key if",
"%s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at the given internal",
"'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab':",
"'' try: for line in open(file_name): result += transpose_line(line, direction, to_key) return result",
"Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at the",
"'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'),",
"'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b',",
"('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#',",
"('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A':",
"recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number",
"arguments: file_name = arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s",
"the internal index of a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in",
"keys if it starts with a pipe. Examples: >>> transpose_line('| A | A#",
"= get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key, to_key):",
"a chord a number of half tones. Sharp or flat depends on target",
"Bb | C#m7/F# |', -2, 'D') '| G | G# | G# |",
"|', -2, 'C') 'A | Bb |' \"\"\" if source_line[0] != '|': return",
"key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones to",
"len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction,",
"to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key)",
"-2, 'C') 'A | Bb |' \"\"\" if source_line[0] != '|': return source_line",
"return get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:' print() '%s --from=Eb --to=F#",
"transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E | A B | Cm7#11/D#",
"'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index",
"1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the",
"transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a key to another. >>> transpose_file('example.txt',",
"be sharp or flat depending on target key. >>> transpose_line('| A | A#",
"direction, to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or not source_line:",
"will use the more common key if sharp/flat, for example F# instead of",
"key. >>> transpose('C', 3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index +",
"target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a key",
"'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option,",
"if it starts with a pipe. Examples: >>> transpose_line('| A | A# |",
"+= transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line,",
"= source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] +",
"transpose(source_chord, direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key):",
"transpose_line('| Gb |', 0, 'Gb') '| F# |' Lines not starting with pipe",
"transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number of keys if it starts",
"('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#',",
"from a key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n|",
"sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b',",
"number of half tones. Sharp or flat depends on target key. >>> transpose('C',",
"|\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result = '' try: for line in",
"Sharp or flat depends on the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\"",
">>> transpose_line('| A | A# | Bb | C#m7/F# |', -2, 'D') '|",
"except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option, value in options: if",
"jazzy ending\\\\n| E | A B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key,",
"'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage():",
"tones. Sharp or flat depends on target key. >>> transpose('C', 3, 'Bb') 'Eb'",
"'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#',",
"\"\"\"Transposes a chord a number of half tones. Sharp or flat depends on",
"'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A': '#',",
"number of half tones to transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index =",
"\"\"\" direction = get_transponation_steps(from_key, to_key) result = '' try: for line in open(file_name):",
"- source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a key to",
"['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#',",
"direction, to_key): \"\"\"Transposes a chord a number of half tones. Sharp or flat",
"= get_transponation_steps(from_key, to_key) result = '' try: for line in open(file_name): result +=",
"return result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a",
"return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones",
"pipe. Examples: >>> transpose_line('| A | A# | Bb | C#m7/F# |', -2,",
"target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names = key_list[index % len(key_list)] if",
"source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index]",
"exit() else: usage() if arguments: file_name = arguments[0] else: usage() result = transpose_file(file_name,",
"-2, 'D') '| G | G# | G# | Bm7/E |' It will",
"'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index",
"source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:' print()",
"doctest doctest.testmod() exit() else: usage() if arguments: file_name = arguments[0] else: usage() result",
"'D#': 'b', 'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G':",
"input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key = 'C' to_key = 'C' file_name",
"} key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of a key",
"\"\"\"Transposes a line a number of keys if it starts with a pipe.",
"to_key) return result except IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes",
"'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E': '#', 'F':",
"It will use the more common key if sharp/flat, for example F# instead",
"= get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file",
"internal index of a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list:",
"None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as",
"transpose >>> get_transponation_steps('D', 'C') -2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return",
"os import re, getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#',",
"\"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def usage(): print() 'Usage:'",
"[('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',),",
"| A# | Bb | C#m7/F# |', -2, 'C') '| G | Ab",
"| Ab | Ab | Bm7/E |' Different keys will be sharp or",
"the more common key if sharp/flat, for example F# instead of Gb. >>>",
"'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat =",
"keys will be sharp or flat depending on target key. >>> transpose_line('| A",
"| C#m7/F# |', -2, 'C') '| G | Ab | Ab | Bm7/E",
"filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number of keys",
"result += transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid filename!\") usage() def",
"line in open(file_name): result += transpose_line(line, direction, to_key) return result except IOError: print(\"Invalid",
"\"\"\" for key_names in key_list: if source_key in key_names: return key_list.index(key_names) raise Exception(\"Invalid",
"\\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a",
"key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E |",
"source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key,",
"try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=', 'doctest']) except getopt.GetoptError as err:",
"Ab | Bm7/E |' Different keys will be sharp or flat depending on",
"get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if source_key in key_names: return key_list.index(key_names)",
"source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] + \\",
"source_chords or not source_line: return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index",
"get_transponation_steps(source_key, target_key): \"\"\"Gets the number of half tones to transpose >>> get_transponation_steps('D', 'C')",
"target key. >>> transpose_line('| A | A# | Bb | C#m7/F# |', -2,",
"Ab | Ab | Bm7/E |' Different keys will be sharp or flat",
"to_key) def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or not source_line: return",
"re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key): \"\"\"Gets the internal index of a key >>> get_index_from_key('Bb') 1",
"'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b', }",
"G# | Bm7/E |' It will use the more common key if sharp/flat,",
"['from=', 'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option, value",
"of keys if it starts with a pipe. Examples: >>> transpose_line('| A |",
"to_key = value elif option == '--doctest': import doctest doctest.testmod() exit() else: usage()",
"line a number of keys if it starts with a pipe. Examples: >>>",
"depending on target key. >>> transpose_line('| A | A# | Bb | C#m7/F#",
"to_key): \"\"\"Transposes a chord a number of half tones. Sharp or flat depends",
"def get_index_from_key(source_key): \"\"\"Gets the internal index of a key >>> get_index_from_key('Bb') 1 \"\"\"",
"get_key_from_index(index, to_key): \"\"\"Gets the key at the given internal index. Sharp or flat",
"'Bb': 'b', 'B': '#', 'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#':",
"-2 \"\"\" source_index = get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index def",
"more common key if sharp/flat, for example F# instead of Gb. >>> transpose_line('|",
"'|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction, to_key) def recursive_line_transpose(source_line,",
">>> transpose_file('example.txt', 'D', 'E') 'Rocking start, jazzy ending\\\\n| E | A B |",
"or flat depends on the target key. >>> get_key_from_index(1, 'Eb') 'Bb' \"\"\" key_names",
"E | A B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result",
"raise Exception(\"Invalid key: %s\" % source_key) def get_key_from_index(index, to_key): \"\"\"Gets the key at",
"get_index_from_key(source_key): \"\"\"Gets the internal index of a key >>> get_index_from_key('Bb') 1 \"\"\" for",
"Different keys will be sharp or flat depending on target key. >>> transpose_line('|",
"else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" % (from_key,",
"in ('-f', '--from'): from_key = value elif option in ('-t', '--to'): to_key =",
"'Eb': 'b', 'E': '#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#':",
"sharp/flat, for example F# instead of Gb. >>> transpose_line('| Gb |', 0, 'Gb')",
"starting with pipe will not be transposed >>> transpose_line('A | Bb |', -2,",
"| Bb | C#m7/F# |', -2, 'D') '| G | G# | G#",
"| Bm7/E |' Different keys will be sharp or flat depending on target",
"+ direction, to_key) def usage(): print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' %",
"target_index = get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a",
"def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number of half tones. Sharp",
"|' It will use the more common key if sharp/flat, for example F#",
"direction, to_key) + \\ recursive_line_transpose(source_line[after_chord_index:], source_chords, direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes",
"Bm7/E |' Different keys will be sharp or flat depending on target key.",
"not be transposed >>> transpose_line('A | Bb |', -2, 'C') 'A | Bb",
"option, value in options: if option in ('-f', '--from'): from_key = value elif",
"'#', 'F': 'b', 'F#': '#', 'Gb': '#', 'G': '#', 'G#': 'b', 'Ab': 'b',",
"direction = get_transponation_steps(from_key, to_key) result = '' try: for line in open(file_name): result",
"if option in ('-f', '--from'): from_key = value elif option in ('-t', '--to'):",
"import sys import os import re, getopt key_list = [('A',), ('A#', 'Bb'), ('B',",
"= arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\"",
"Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result = '' try: for line",
"def recursive_line_transpose(source_line, source_chords, direction, to_key): if not source_chords or not source_line: return source_line",
"get_index_from_key(source_key) target_index = get_index_from_key(target_key) return target_index - source_index def transpose_file(file_name, from_key, to_key): \"\"\"Transposes",
"the given internal index. Sharp or flat depends on the target key. >>>",
"'C': 'b', 'C#': 'b', 'Db': 'b', 'D': '#', 'D#': 'b', 'Eb': 'b', 'E':",
"with pipe will not be transposed >>> transpose_line('A | Bb |', -2, 'C')",
"\"\"\" key_names = key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key])",
"'to=', 'doctest']) except getopt.GetoptError as err: print(str(err), usage(), sys.exit(2)) for option, value in",
"| A B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key) result =",
"transposed >>> transpose_line('A | Bb |', -2, 'C') 'A | Bb |' \"\"\"",
"'#', 'G': '#', 'G#': 'b', 'Ab': 'b', } key_regex = re.compile(r\"[ABCDEFG][#b]?\") def get_index_from_key(source_key):",
"if source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line, source_chords, direction,",
"in ('-t', '--to'): to_key = value elif option == '--doctest': import doctest doctest.testmod()",
"err: print(str(err), usage(), sys.exit(2)) for option, value in options: if option in ('-f',",
"3, 'Bb') 'Eb' \"\"\" source_index = get_index_from_key(source_chord) return get_key_from_index(source_index + direction, to_key) def",
"print() 'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key",
"direction, to_key): \"\"\"Transposes a line a number of keys if it starts with",
"index of a key >>> get_index_from_key('Bb') 1 \"\"\" for key_names in key_list: if",
"ending\\\\n| E | A B | Cm7#11/D# |\\\\n' \"\"\" direction = get_transponation_steps(from_key, to_key)",
"file_name = arguments[0] else: usage() result = transpose_file(file_name, from_key, to_key) print(\"Result (%s ->",
"C#m7/F# |', -2, 'C') '| G | Ab | Ab | Bm7/E |'",
"G# | G# | Bm7/E |' It will use the more common key",
"to_key): \"\"\"Transposes a file from a key to another. >>> transpose_file('example.txt', 'D', 'E')",
"usage(), sys.exit(2)) for option, value in options: if option in ('-f', '--from'): from_key",
"def transpose_file(file_name, from_key, to_key): \"\"\"Transposes a file from a key to another. >>>",
"source_line.find(source_chord) after_chord_index = chord_index + len(source_chord) return source_line[:chord_index] + \\ transpose(source_chord, direction, to_key)",
"F# |' Lines not starting with pipe will not be transposed >>> transpose_line('A",
"|' \"\"\" if source_line[0] != '|': return source_line source_chords = key_regex.findall(source_line) return recursive_line_transpose(source_line,",
"('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = {",
"to_key): \"\"\"Gets the key at the given internal index. Sharp or flat depends",
"number of keys if it starts with a pipe. Examples: >>> transpose_line('| A",
"'Ab')] sharp_flat = ['#', 'b'] sharp_flat_preferences = { 'A': '#', 'A#': 'b', 'Bb':",
"def get_key_from_index(index, to_key): \"\"\"Gets the key at the given internal index. Sharp or",
"| Bb | C#m7/F# |', -2, 'C') '| G | Ab | Ab",
"transpose_file(file_name, from_key, to_key) print(\"Result (%s -> %s):\" % (from_key, to_key)) print(result) if __name__",
"IOError: print(\"Invalid filename!\") usage() def transpose_line(source_line, direction, to_key): \"\"\"Transposes a line a number",
"('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#', 'Ab')]",
"sys import os import re, getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'),",
"'C' to_key = 'C' file_name = None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:',",
"direction, to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number of half",
"= { 'A': '#', 'A#': 'b', 'Bb': 'b', 'B': '#', 'C': 'b', 'C#':",
"C#m7/F# |', -2, 'D') '| G | G# | G# | Bm7/E |'",
"to_key) result = '' try: for line in open(file_name): result += transpose_line(line, direction,",
"option in ('-t', '--to'): to_key = value elif option == '--doctest': import doctest",
"'Usage:' print() '%s --from=Eb --to=F# input_filename' % os.path.basename(__file__) sys.exit(2) def main(): from_key =",
"> 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return key_names[sharp_or_flat] return key_names[0] def get_transponation_steps(source_key, target_key): \"\"\"Gets",
"'D', 'E') 'Rocking start, jazzy ending\\\\n| E | A B | Cm7#11/D# |\\\\n'",
"Gb. >>> transpose_line('| Gb |', 0, 'Gb') '| F# |' Lines not starting",
"import re, getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'),",
"\"\"\"Transposes a file from a key to another. >>> transpose_file('example.txt', 'D', 'E') 'Rocking",
"key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'),",
"getopt key_list = [('A',), ('A#', 'Bb'), ('B', 'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#',",
"print(str(err), usage(), sys.exit(2)) for option, value in options: if option in ('-f', '--from'):",
"key_names = key_list[index % len(key_list)] if len(key_names) > 1: sharp_or_flat = sharp_flat.index(sharp_flat_preferences[to_key]) return",
"'Cb'), ('C',), ('C#', 'Db'), ('D',), ('D#', 'Eb'), ('E',), ('F',), ('F#', 'Gb'), ('G',), ('G#',",
"of Gb. >>> transpose_line('| Gb |', 0, 'Gb') '| F# |' Lines not",
"or not source_line: return source_line source_chord = source_chords.pop(0) chord_index = source_line.find(source_chord) after_chord_index =",
"= 'C' file_name = None try: options, arguments = getopt.getopt(sys.argv[1:], 'f:t:', ['from=', 'to=',",
"to_key) def transpose(source_chord, direction, to_key): \"\"\"Transposes a chord a number of half tones."
] |
[
"articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list():",
"request from flask import jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__)",
"from flask import jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service",
"return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method ==",
"render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET':",
"flask import jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service =",
"from flask import Blueprint from flask import render_template from flask import request from",
"methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles)",
"..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page():",
"flask import Blueprint from flask import render_template from flask import request from flask",
"from flask import request from flask import jsonify from ..services import ArticlesService blog_views",
"def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"])",
"articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\",",
"return jsonify(articles) elif request.method == 'POST': article_title = request.json['title'] article_content = request.json['content'] articles_service.addArticle(article_title,",
"def display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method",
"\"POST\"]) def display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles) elif",
"articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title = request.json['title'] article_content = request.json['content']",
"ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles',",
"import request from flask import jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views',",
"import Blueprint from flask import render_template from flask import request from flask import",
"ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles =",
"if request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method == 'POST':",
"import render_template from flask import request from flask import jsonify from ..services import",
"= ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", )",
"import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles",
"current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET': articles =",
"Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html',",
"elif request.method == 'POST': article_title = request.json['title'] article_content = request.json['content'] articles_service.addArticle(article_title, article_content) return",
"<reponame>aHugues/blog from flask import Blueprint from flask import render_template from flask import request",
"__name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles,",
"display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method ==",
") @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles()",
"== 'POST': article_title = request.json['title'] article_content = request.json['content'] articles_service.addArticle(article_title, article_content) return \"ok\", 200",
"render_template from flask import request from flask import jsonify from ..services import ArticlesService",
"from flask import render_template from flask import request from flask import jsonify from",
"@blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET': articles = articles_service.listArticles() return",
"flask import request from flask import jsonify from ..services import ArticlesService blog_views =",
"import jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService()",
"'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title = request.json['title']",
"Blueprint from flask import render_template from flask import request from flask import jsonify",
"blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles()",
"= Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return",
"@blog_views.route('/blog') def home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\",",
"= articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title = request.json['title'] article_content =",
"from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog') def",
"request.method == 'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title",
"== 'GET': articles = articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title =",
"articles = articles_service.listArticles() return jsonify(articles) elif request.method == 'POST': article_title = request.json['title'] article_content",
"= articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if",
"articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method == 'GET': articles",
"flask import render_template from flask import request from flask import jsonify from ..services",
"jsonify(articles) elif request.method == 'POST': article_title = request.json['title'] article_content = request.json['content'] articles_service.addArticle(article_title, article_content)",
"jsonify from ..services import ArticlesService blog_views = Blueprint('blog_views', __name__) articles_service = ArticlesService() @blog_views.route('/blog')",
"home_page(): articles = articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def",
"request.method == 'POST': article_title = request.json['title'] article_content = request.json['content'] articles_service.addArticle(article_title, article_content) return \"ok\",",
"articles_service.listArticles() return render_template('blog.html', articles=articles, current_page=\"blog\", ) @blog_views.route('/api/articles', methods=[\"GET\", \"POST\"]) def display_articles_list(): if request.method"
] |
[
"execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language,",
"import subprocess from typing import Optional from celery import Celery from celery.utils.log import",
"maximum time the code is allowed to run @return: dict containgin execution results",
"executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def execute_code(language:",
"\"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned,",
"from typing import Optional from celery import Celery from celery.utils.log import get_logger from",
"to wait for infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # )",
"CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output",
"order to wait for infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True #",
"tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app and get",
"language: code programming language @param code: code to be executed @param submission: flag",
"in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file,",
"logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait",
"0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file,",
"execution @param language: code programming language @param code: code to be executed @param",
"} try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result:",
"= 10) -> dict: \"\"\" Task for code execution @param language: code programming",
"= True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] = \"Time Limit Exceeded\"",
"celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path =",
"{ \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try:",
"code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True",
"code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files'",
"Celery from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from utils import generate_random_file",
"@param timeout: maximum time the code is allowed to run @return: dict containgin",
"generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app and",
"False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code,",
"import Optional from celery import Celery from celery.utils.log import get_logger from code_execution.code_execution import",
"broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait for infinite loop code",
"tells if the code to be executed is a submission or a normal",
"default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"]",
"errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired",
"submission: bool = False, timeout: Optional[float] = 10) -> dict: \"\"\" Task for",
"code programming language @param code: code to be executed @param submission: flag which",
"dict containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file",
"loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task",
"timeout: maximum time the code is allowed to run @return: dict containgin execution",
"code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"]",
"the code is allowed to run @return: dict containgin execution results \"\"\" logger.info(\"Starting",
"def execute_code(language: str, code: str, submission: bool = False, timeout: Optional[float] = 10)",
"= CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] =",
"@param language: code programming language @param code: code to be executed @param submission:",
"cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"]",
"as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"]",
"False, timeout: Optional[float] = 10) -> dict: \"\"\" Task for code execution @param",
"celery import Celery from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from utils",
"code to be executed is a submission or a normal execution @param timeout:",
"from celery import Celery from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from",
"utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery",
"and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in",
"-> dict: \"\"\" Task for code execution @param language: code programming language @param",
"\"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output",
"in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError",
"\"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path,",
"cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"]",
"default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] =",
"dict: \"\"\" Task for code execution @param language: code programming language @param code:",
"execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output",
"celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code:",
"subprocess from typing import Optional from celery import Celery from celery.utils.log import get_logger",
"code: code to be executed @param submission: flag which tells if the code",
"{cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as",
"cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"]",
"the code to be executed is a submission or a normal execution @param",
"10) -> dict: \"\"\" Task for code execution @param language: code programming language",
"for infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger =",
"Optional from celery import Celery from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution",
"= '/worker/tmp/compiled_files' # Create the celery app and get the logger celery_app =",
"False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output =",
"import logging import subprocess from typing import Optional from celery import Celery from",
"to be executed is a submission or a normal execution @param timeout: maximum",
"to run @return: dict containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path =",
"code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe:",
"code execution @param language: code programming language @param code: code to be executed",
"get_logger from code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path",
"CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\":",
"submission: flag which tells if the code to be executed is a submission",
") logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission: bool =",
"command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except",
"or a normal execution @param timeout: maximum time the code is allowed to",
"logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] =",
"(f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict",
"backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait for infinite loop code executions",
"= False, timeout: Optional[float] = 10) -> dict: \"\"\" Task for code execution",
"was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except",
"default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] = \"Time Limit Exceeded\" return default_dict",
"app and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE",
"be executed is a submission or a normal execution @param timeout: maximum time",
"after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] =",
"= code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] =",
"normal execution @param timeout: maximum time the code is allowed to run @return:",
"celery app and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add",
"the celery app and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') #",
"Create the celery app and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//')",
"a submission or a normal execution @param timeout: maximum time the code is",
"result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored:",
"default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] = \"Time Limit",
"to be executed @param submission: flag which tells if the code to be",
"code is allowed to run @return: dict containgin execution results \"\"\" logger.info(\"Starting code",
"timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"]",
"get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission: bool = False, timeout: Optional[float]",
"if the code to be executed is a submission or a normal execution",
"code to be executed @param submission: flag which tells if the code to",
"time the code is allowed to run @return: dict containgin execution results \"\"\"",
"language, compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\":",
"timeout: Optional[float] = 10) -> dict: \"\"\" Task for code execution @param language:",
"f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict =",
"bool = False, timeout: Optional[float] = 10) -> dict: \"\"\" Task for code",
"str, submission: bool = False, timeout: Optional[float] = 10) -> dict: \"\"\" Task",
"= True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code",
"language @param code: code to be executed @param submission: flag which tells if",
"= get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission: bool = False, timeout:",
"import Celery from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from utils import",
"Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was",
"a normal execution @param timeout: maximum time the code is allowed to run",
"{te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] = \"Time",
"logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command(",
"= cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\")",
"Optional[float] = 10) -> dict: \"\"\" Task for code execution @param language: code",
"infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__)",
"CELERY_ACKS_LATE in order to wait for infinite loop code executions # celery_app.conf.update( #",
"from code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path =",
"= Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait for infinite",
"programming language @param code: code to be executed @param submission: flag which tells",
"run @return: dict containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\"",
"be executed @param submission: flag which tells if the code to be executed",
"celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait for",
"executed @param submission: flag which tells if the code to be executed is",
"default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\"",
"typing import Optional from celery import Celery from celery.utils.log import get_logger from code_execution.code_execution",
"containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file =",
"@param submission: flag which tells if the code to be executed is a",
"= CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\": False,",
"compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = {",
"except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] =",
"te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] =",
"@celery_app.task def execute_code(language: str, code: str, submission: bool = False, timeout: Optional[float] =",
"subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] =",
"which tells if the code to be executed is a submission or a",
"Add CELERY_ACKS_LATE in order to wait for infinite loop code executions # celery_app.conf.update(",
"execute_code(language: str, code: str, submission: bool = False, timeout: Optional[float] = 10) ->",
"logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True",
"'/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app and get the logger",
"@param code: code to be executed @param submission: flag which tells if the",
"# CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code: str,",
"= (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission)",
"f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = { \"has_error\": False,",
"\"out_of_time\": False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code,",
"allowed to run @return: dict containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path",
"in order to wait for infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True",
"\"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code =",
"code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path,",
"submission) default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\":",
"in_file_path, language, compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0,",
"wait for infinite loop code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger",
"False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout)",
"'/worker/tmp/compiled_files' # Create the celery app and get the logger celery_app = Celery('code-executions-tasks',",
"from celery.utils.log import get_logger from code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path",
"# Add CELERY_ACKS_LATE in order to wait for infinite loop code executions #",
"logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission: bool = False,",
"compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as",
"as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode",
"get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order",
"flag which tells if the code to be executed is a submission or",
"@return: dict containgin execution results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\")",
"CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission:",
"execution results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out'",
"Task for code execution @param language: code programming language @param code: code to",
"is a submission or a normal execution @param timeout: maximum time the code",
"= f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = { \"has_error\":",
"= { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" }",
"# Create the celery app and get the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//',",
"execution @param timeout: maximum time the code is allowed to run @return: dict",
"\"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False, \"raw_output\": \"\" } try: code_output = CodeExcution.execute_code(",
"True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout",
"True default_dict[\"exit_code\"] = 124 default_dict[\"out_of_time\"] = True default_dict[\"raw_output\"] = \"Time Limit Exceeded\" return",
"compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app and get the logger celery_app",
"Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to wait for infinite loop",
"submission or a normal execution @param timeout: maximum time the code is allowed",
"CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create",
"\"raw_output\": \"\" } try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code",
"try: code_output = CodeExcution.execute_code( command_to_execute_code, in_file_path, compiled_file, code, timeout) logging.info(f\"Code Returned, result: {code_output}\")",
"except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"]",
"# ) logger = get_logger(__name__) @celery_app.task def execute_code(language: str, code: str, submission: bool",
"code: str, submission: bool = False, timeout: Optional[float] = 10) -> dict: \"\"\"",
"for code execution @param language: code programming language @param code: code to be",
"default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after:",
"timeout) logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code",
"logging import subprocess from typing import Optional from celery import Celery from celery.utils.log",
"executed is a submission or a normal execution @param timeout: maximum time the",
"import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app",
"results \"\"\" logger.info(\"Starting code execution\") in_file_path = (f\"{tmp_dir_path}/in_files/{generate_random_file()}.\" f\"{CodeExcution.get_lang_extension(language)}\") compiled_file = f'{compiled_dir_path}/{generate_random_file()}.out' command_to_execute_code",
"logging.info(f\"Code Returned, result: {code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution",
"\"\"\" Task for code execution @param language: code programming language @param code: code",
"is allowed to run @return: dict containgin execution results \"\"\" logger.info(\"Starting code execution\")",
"compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\": False, \"exit_code\": 0, \"out_of_time\": False,",
"str, code: str, submission: bool = False, timeout: Optional[float] = 10) -> dict:",
"= cpe.output except subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True",
"subprocess.TimeoutExpired as te: logger.debug(f\"Code timeout after: {te.timeout}\") default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = 124",
"code executions # celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def",
"command_to_execute_code = CodeExcution.provide_code_execution_command( in_file_path, language, compiled_file, submission) default_dict = { \"has_error\": False, \"out_of_resources\":",
"from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the",
"{code_output}\") default_dict[\"raw_output\"] = code_output except subprocess.CalledProcessError as cpe: logging.debug(f\"Code execution was errored: {cpe}\")",
"import CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' #",
"# celery_app.conf.update( # CELERY_ACKS_LATE=True # ) logger = get_logger(__name__) @celery_app.task def execute_code(language: str,",
"default_dict[\"has_error\"] = True default_dict[\"exit_code\"] = cpe.returncode default_dict[\"raw_output\"] = cpe.output except subprocess.TimeoutExpired as te:",
"= '/worker/tmp' compiled_dir_path = '/worker/tmp/compiled_files' # Create the celery app and get the",
"import get_logger from code_execution.code_execution import CodeExcution from utils import generate_random_file tmp_dir_path = '/worker/tmp'",
"the logger celery_app = Celery('code-executions-tasks', broker='pyamqp://guest@rabbit//', backend='amqp://guest@rabbit//') # Add CELERY_ACKS_LATE in order to"
] |
[
"self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 =",
"np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input response.pm10_data =",
"random import time from concurrent import futures import grpc import databroker_pb2_grpc import databroker_pb2",
"import random import time from concurrent import futures import grpc import databroker_pb2_grpc import",
"#add output to response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input",
"#imports import haversine as hs import pandas as pd import numpy as np",
"import grpc import databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self):",
"= distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:])",
"= no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1 to row counter(maybe",
"0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv')",
"data has been processed\") else: #load 1 row from each dataset and convert",
"for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1",
"= self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] =",
"pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to",
"pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response =",
"#host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port :",
"on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while True: time.sleep(86400) except",
"pm10_input response.pm25_data = pm25_input #add 1 to row counter(maybe we could make it",
": \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while True: time.sleep(86400) except KeyboardInterrupt: server.stop(0)",
"# create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns)",
"Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data",
"has been processed\") else: #load 1 row from each dataset and convert to",
"we could make it cyclical with mod later) self.current_row += 1 return response",
"= pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input =",
"no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input =",
"= pm25_input #add 1 to row counter(maybe we could make it cyclical with",
"pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv')",
"cyclical with mod later) self.current_row += 1 return response #host server server =",
"with mod later) self.current_row += 1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))",
"print(\"Starting server. Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while",
"from concurrent import futures import grpc import databroker_pb2_grpc import databroker_pb2 port = 8061",
"pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input",
"databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start()",
"= pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features() if",
"dataset and convert to numpy # create response format dataframe no2 = pd.DataFrame(data=None,",
"= np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data",
"self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features()",
"else: #load 1 row from each dataset and convert to numpy # create",
"haversine as hs import pandas as pd import numpy as np import random",
"= np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1,",
"def get_next(self, request, context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all",
"range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1",
"required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data =",
"np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data =",
"in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4])",
"from each dataset and convert to numpy # create response format dataframe no2",
"counter(maybe we could make it cyclical with mod later) self.current_row += 1 return",
"server. Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while True:",
"pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features() if self.current_row",
"np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2,",
"it cyclical with mod later) self.current_row += 1 return response #host server server",
"hs import pandas as pd import numpy as np import random import time",
"server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port : \"",
"= hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] =",
"as np import random import time from concurrent import futures import grpc import",
"(lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1",
"= 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data =",
"response.pm25_data = pm25_input #add 1 to row counter(maybe we could make it cyclical",
"processed\") else: #load 1 row from each dataset and convert to numpy #",
"no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy()",
"pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request,",
"import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load",
"range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2]",
"+= 1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server.",
"pd import numpy as np import random import time from concurrent import futures",
"= databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else:",
"pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input",
"= self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] =",
"+=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input=",
"port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while True: time.sleep(86400) except KeyboardInterrupt:",
"concurrent import futures import grpc import databroker_pb2_grpc import databroker_pb2 port = 8061 class",
"= pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i",
"server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port : \" +",
"response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1 to row counter(maybe we could",
"import numpy as np import random import time from concurrent import futures import",
"databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required",
"= pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response",
"lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2",
"create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25",
"self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 =",
"output to response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add",
"pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id",
"= np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data",
"for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1]",
"no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for",
"self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load 1 row",
"pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input)",
"= pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]:",
"pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for",
"datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv')",
"request, context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has",
"lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter]",
"no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1 to row counter(maybe we",
"np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1))",
"make it cyclical with mod later) self.current_row += 1 return response #host server",
"context.set_details(\"all data has been processed\") else: #load 1 row from each dataset and",
"= np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input response.pm10_data",
"sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 =",
"def __init__(self): self.current_row = 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data =",
"pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input",
"get_next(self, request, context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data",
"import databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row =",
"convert to numpy # create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10",
"hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance",
"each dataset and convert to numpy # create response format dataframe no2 =",
"pm25_input #add 1 to row counter(maybe we could make it cyclical with mod",
"counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy()",
"row from each dataset and convert to numpy # create response format dataframe",
"port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required datasets",
"pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output",
"to row counter(maybe we could make it cyclical with mod later) self.current_row +=",
"= grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port : \" + str(port))",
"no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input",
"return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on",
"np import random import time from concurrent import futures import grpc import databroker_pb2_grpc",
"distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25",
"self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps",
"8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required datasets self.no2_data =",
"response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port",
"np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data =",
"#add 1 to row counter(maybe we could make it cyclical with mod later)",
"= 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required datasets self.no2_data",
"numpy # create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None,",
"columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]):",
"format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None,",
"self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features() if self.current_row >=",
"response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1 to",
"distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter]",
"self.current_row += 1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting",
"import time from concurrent import futures import grpc import databroker_pb2_grpc import databroker_pb2 port",
"import futures import grpc import databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer):",
"time from concurrent import futures import grpc import databroker_pb2_grpc import databroker_pb2 port =",
"response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1 to row",
"= pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id =",
"databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load",
"pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in",
"databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0",
"pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor]",
"grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port))",
"1 to row counter(maybe we could make it cyclical with mod later) self.current_row",
"been processed\") else: #load 1 row from each dataset and convert to numpy",
"pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND)",
"self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2",
"context): response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been",
"Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try: while True: time.sleep(86400)",
"could make it cyclical with mod later) self.current_row += 1 return response #host",
"lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter]",
"futures import grpc import databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def",
"import haversine as hs import pandas as pd import numpy as np import",
"pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input)",
"= pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input =",
"if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load 1",
">= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load 1 row from",
"to numpy # create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 =",
"mod later) self.current_row += 1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(),",
"i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2",
"numpy as np import random import time from concurrent import futures import grpc",
"self.current_row = 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data",
"#load 1 row from each dataset and convert to numpy # create response",
"distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10",
"row counter(maybe we could make it cyclical with mod later) self.current_row += 1",
"server) print(\"Starting server. Listening on port : \" + str(port)) server.add_insecure_port(\"[::]:{}\".format(port)) server.start() try:",
"= np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance =",
"= distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:])",
"1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server) print(\"Starting server. Listening",
"context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load 1 row from each dataset",
"pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add",
"lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance",
"in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 =",
"distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input=",
"and convert to numpy # create response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns)",
"counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 =",
"lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter",
"columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1):",
"as hs import pandas as pd import numpy as np import random import",
"import pandas as pd import numpy as np import random import time from",
"= pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps =",
"= pm10_input response.pm25_data = pm25_input #add 1 to row counter(maybe we could make",
"later) self.current_row += 1 return response #host server server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) databroker_pb2_grpc.add_DatabrokerServicer_to_server(Databroker(), server)",
"#load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data",
"no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input) #add output to response",
"self.pm10_data = pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def",
"grpc import databroker_pb2_grpc import databroker_pb2 port = 8061 class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row",
"pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1 for i in",
"__init__(self): self.current_row = 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv') self.pm10_data = pd.read_csv('./data/pm10_testset.csv')",
"pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input= pm25.iloc[:,1:].to_numpy() no2_input = np.ndarray.tobytes(no2_input) pm10_input = np.ndarray.tobytes(pm10_input) pm25_input = np.ndarray.tobytes(pm25_input)",
"self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance self.pm10_data.iloc[self.current_row,counter] = distance",
"as pd import numpy as np import random import time from concurrent import",
"response = databroker_pb2.Features() if self.current_row >= self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\")",
"self.no2_data.shape[0]: context.set_code(grpc.StatusCode.NOT_FOUND) context.set_details(\"all data has been processed\") else: #load 1 row from each",
"= distance self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:])",
"self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self, request, context):",
"lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5]) lat2 = self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2),",
"columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor in range(self.sensor_gps.shape[0]): id = self.sensor_gps.deviceID[sensor] counter=1",
"= pd.read_csv('./data/pm10_testset.csv') self.pm25_data = pd.read_csv('./data/pm25_testset.csv') self.gps_data = pd.read_csv('./data/sensor_gps.csv') self.sensor_gps = pd.read_csv('./data/low_cost_sensors.csv') def get_next(self,",
"= self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 = np.rad2deg(self.sensor_gps.iloc[sensor,5])",
"response format dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 =",
"self.pm10_data.iloc[self.current_row,counter] = distance self.pm25_data.iloc[self.current_row,counter] = distance counter +=1 no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 =",
"dataframe no2 = pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns)",
"pandas as pd import numpy as np import random import time from concurrent",
"pm25_input = np.ndarray.tobytes(pm25_input) #add output to response response.no2_data = no2_input response.pm10_data = pm10_input",
"id = self.sensor_gps.deviceID[sensor] counter=1 for i in range(23,0,-1): lat1 = np.rad2deg(self.sensor_gps.iloc[sensor,4]) lon1 =",
"no2 = no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy()",
"= pd.DataFrame(data=None, columns=self.no2_data.columns) pm10 = pd.DataFrame(data=None, columns=self.pm10_data.columns) pm25 = pd.DataFrame(data=None, columns=self.pm25_data.columns) for sensor",
"self.gps_data.iloc[0,i*2+1] lon2 = self.gps_data.iloc[0,i*2] distance = hs.haversine((lat2, lon2), (lat1, lon1)) self.no2_data.iloc[self.current_row,counter] = distance",
"= no2.append(self.no2_data.iloc[self.current_row,:]) pm10 = pm10.append(self.pm10_data.iloc[self.current_row,:]) pm25 = pm25.append(self.pm25_data.iloc[self.current_row,:]) no2_input= no2.iloc[:,1:].to_numpy() pm10_input= pm10.iloc[:,1:].to_numpy() pm25_input=",
"to response response.no2_data = no2_input response.pm10_data = pm10_input response.pm25_data = pm25_input #add 1",
"class Databroker(databroker_pb2_grpc.DatabrokerServicer): def __init__(self): self.current_row = 0 #load required datasets self.no2_data = pd.read_csv('./data/no2_testset.csv')",
"1 row from each dataset and convert to numpy # create response format"
] |
[
"to get default value and might fail # if the field has some",
"[] else: self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults",
"in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options",
"[field for field in self.fields if field.arg_options] if len(option_fields) > 0: # Only",
"some required arguments logger.debug( f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying Error:",
"= False self._dest: str = \"\" self._children: List[DataclassWrapper] = [] self._parent = parent",
"= prefix self.fields: List[FieldWrapper] = [] self._required: bool = False self._explicit: bool =",
"__init__( self, dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict] = None,",
"True self._children.append(child_wrapper) else: # a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug(",
"doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base",
"= getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError as e:",
"exists title += f\" ['{self.dest}']\" return title @property def description(self) -> str: if",
"Show name if exists title += f\" ['{self.dest}']\" return title @property def description(self)",
"= value @property def descendants(self): for child in self._children: yield child yield from",
"docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not None: if doc.docstring_below: return doc.docstring_below",
"[] for default in self.parent.defaults: if default is None: default = None else:",
"cast from pyrallis.utils import Dataclass from . import docstring from .field_wrapper import FieldWrapper",
"if exists title += f\" ['{self.dest}']\" return title @property def description(self) -> str:",
"if default: self.defaults = [default] self.optional: bool = False for field in dataclasses.fields(self.dataclass):",
"attribute {self.dest} has default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing",
"= None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass",
"looks confusing, remove it return class_doc @property def required(self) -> bool: return self._required",
"parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field",
"attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a",
"logger.debug( f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value =",
"description(self) -> str: if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name )",
"{field_wrapper.dest} has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at",
"bool): self._required = value for field in self.fields: field.required = value for child_wrapper",
"name) self.dataclass = dataclass self._name = name self.default = default self.prefix = prefix",
"# super().__init__(dataclass, name) self.dataclass = dataclass self._name = name self.default = default self.prefix",
"which contains this child dataclass. self._field = _field # the default values self._defaults:",
"= dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value] return",
"@defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value @property def title(self) -> str:",
"bool = False self._dest: str = \"\" self._children: List[DataclassWrapper] = [] self._parent =",
"construct the field to get default value and might fail # if the",
"add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields =",
"logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property",
"is None: default = None else: default = getattr(default, self.name) self._defaults.append(default) else: try:",
"_field # the default values self._defaults: List[Dataclass] = [] if default: self.defaults =",
"has some required arguments logger.debug( f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying",
"def defaults(self, value: List[Dataclass]): self._defaults = value @property def title(self) -> str: title",
"self.parent.defaults: self._defaults = [] for default in self.parent.defaults: if default is None: default",
"*wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str: return self._name @property def parent(self)",
"= FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass self._name = name self.default",
"of type {field.type}, which isn't \" f\"supported yet. (container of a dataclass type)\"",
"[default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value @property def",
"for field in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field",
"value for child_wrapper in self._children: child_wrapper.required = value @property def descendants(self): for child",
"else: try: default_field_value = utils.default_value(self._field) except TypeError as e: # utils.default_value tries to",
"dataclass, name = field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field )",
"def __init__( self, dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict] =",
"remove it return class_doc @property def required(self) -> bool: return self._required @required.setter def",
"= name self.default = default self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required:",
"else: self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults =",
"and might fail # if the field has some required arguments logger.debug( f\"Could",
"not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type {field.type},",
".. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass],",
"elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\"",
"+= f\" ['{self.dest}']\" return title @property def description(self) -> str: if self.parent and",
"= value for child_wrapper in self._children: child_wrapper.required = value @property def descendants(self): for",
"self._required @required.setter def required(self, value: bool): self._required = value for field in self.fields:",
"if the field has some required arguments logger.debug( f\"Could not get default value",
"of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute",
"getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str] = None, default:",
"str: if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc",
"contains this child dataclass. self._field = _field # the default values self._defaults: List[Dataclass]",
"default in self.parent.defaults: if default is None: default = None else: default =",
"default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE):",
"field in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name}",
"from pyrallis.utils import Dataclass from . import docstring from .field_wrapper import FieldWrapper from",
"the field to get default value and might fail # if the field",
"{e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults =",
"def required(self) -> bool: return self._required @required.setter def required(self, value: bool): self._required =",
"import _MISSING_TYPE from logging import getLogger from typing import Dict, List, Optional, Type,",
"None if self.parent.defaults: self._defaults = [] for default in self.parent.defaults: if default is",
"elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\"",
") for wrapped_field in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" )",
"value for field in self.fields: field.required = value for child_wrapper in self._children: child_wrapper.required",
"field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass",
"_field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass",
"from typing import Dict, List, Optional, Type, Union, cast from pyrallis.utils import Dataclass",
"self.optional: bool = False for field in dataclasses.fields(self.dataclass): if not field.init: continue elif",
"from .. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass:",
"pyrallis.utils import Dataclass from . import docstring from .field_wrapper import FieldWrapper from .wrapper",
"= parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg options for",
"parent # the field of the parent, which contains this child dataclass. self._field",
"self._field = _field # the default values self._defaults: List[Dataclass] = [] if default:",
"in self.fields if field.arg_options] if len(option_fields) > 0: # Only show groups with",
"normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has",
"\" f\"supported yet. (container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle",
"default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError as",
"self._field.name ) if doc is not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above:",
"None: # Show name if exists title += f\" ['{self.dest}']\" return title @property",
"None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass self._name",
"required arguments logger.debug( f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\")",
"child dataclass. self._field = _field # the default values self._defaults: List[Dataclass] = []",
"self._children: child_wrapper.required = value @property def descendants(self): for child in self._children: yield child",
"{field.type}, which isn't \" f\"supported yet. (container of a dataclass type)\" ) elif",
"class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc looks confusing, remove it return",
"TypeError as e: # utils.default_value tries to construct the field to get default",
"dataclass attribute dataclass, name = field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self,",
"Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if",
"value: List[Dataclass]): self._defaults = value @property def title(self) -> str: title = self.dataclass.__qualname__",
"if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is",
"return class_doc @property def required(self) -> bool: return self._required @required.setter def required(self, value:",
"self.fields: field.required = value for child_wrapper in self._children: child_wrapper.required = value @property def",
"List, Optional, Type, Union, cast from pyrallis.utils import Dataclass from . import docstring",
"None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline",
"the parent, which contains this child dataclass. self._field = _field # the default",
"for field in self.fields if field.arg_options] if len(option_fields) > 0: # Only show",
"logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str] =",
"> 0: # Only show groups with parameters group = parser.add_argument_group( title=self.title, description=self.description",
"{wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str: return self._name",
"-> bool: return self._required @required.setter def required(self, value: bool): self._required = value for",
"logger.debug( f\"The dataclass at attribute {self.dest} has default values: {self.defaults}\" ) def add_arguments(self,",
"self.defaults = [default] self.optional: bool = False for field in dataclasses.fields(self.dataclass): if not",
"= False self._explicit: bool = False self._dest: str = \"\" self._children: List[DataclassWrapper] =",
"self._defaults if self._field is None: return [] assert self.parent is not None if",
"title = self.dataclass.__qualname__ if self.dest is not None: # Show name if exists",
"isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value] return self._defaults @defaults.setter def",
"not None if self.parent.defaults: self._defaults = [] for default in self.parent.defaults: if default",
"logging import getLogger from typing import Dict, List, Optional, Type, Union, cast from",
"None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name)",
"yet. (container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested",
"of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has default values:",
"self.parent.defaults: if default is None: default = None else: default = getattr(default, self.name)",
"= None, prefix: str = \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field =",
"self, dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict] = None, prefix:",
"FieldWrapper from .wrapper import Wrapper from .. import utils logger = getLogger(__name__) class",
"if len(option_fields) > 0: # Only show groups with parameters group = parser.add_argument_group(",
"dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass, name",
"{self.dest} has default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import",
"= [field for field in self.fields if field.arg_options] if len(option_fields) > 0: #",
"it return class_doc @property def required(self) -> bool: return self._required @required.setter def required(self,",
"class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass",
"is None: return [] assert self.parent is not None if self.parent.defaults: self._defaults =",
"doc looks confusing, remove it return class_doc @property def required(self) -> bool: return",
"= parent # the field of the parent, which contains this child dataclass.",
"dataclass. self._field = _field # the default values self._defaults: List[Dataclass] = [] if",
"option_fields = [field for field in self.fields if field.arg_options] if len(option_fields) > 0:",
"self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if self._field is",
"None, default: Union[Dataclass, Dict] = None, prefix: str = \"\", parent: \"DataclassWrapper\" =",
"_MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self,",
"from logging import getLogger from typing import Dict, List, Optional, Type, Union, cast",
"= dataclass self._name = name self.default = default self.prefix = prefix self.fields: List[FieldWrapper]",
"self._explicit: bool = False self._dest: str = \"\" self._children: List[DataclassWrapper] = [] self._parent",
"for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) ->",
".wrapper import Wrapper from .. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def",
"name(self) -> str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property",
"self._parent = parent # the field of the parent, which contains this child",
"this child dataclass. self._field = _field # the default values self._defaults: List[Dataclass] =",
"self._required = value for field in self.fields: field.required = value for child_wrapper in",
"import ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field for field in self.fields",
"import getLogger from typing import Dict, List, Optional, Type, Union, cast from pyrallis.utils",
"-> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults",
"= DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type)",
"def name(self) -> str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent",
"if self.dest is not None: # Show name if exists title += f\"",
"type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass, name =",
"self._defaults = [] else: self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self, value:",
"= None else: default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field)",
"title @property def description(self) -> str: if self.parent and self._field: doc = docstring.get_attribute_docstring(",
"self._defaults = [] for default in self.parent.defaults: if default is None: default =",
"def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields",
"default_field_value = utils.default_value(self._field) except TypeError as e: # utils.default_value tries to construct the",
"def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults:",
"default self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required: bool = False self._explicit:",
"is not None if self.parent.defaults: self._defaults = [] for default in self.parent.defaults: if",
"is not None: # Show name if exists title += f\" ['{self.dest}']\" return",
"else: # a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field",
"required(self) -> bool: return self._required @required.setter def required(self, value: bool): self._required = value",
"List[Dataclass]: if self._defaults: return self._defaults if self._field is None: return [] assert self.parent",
"-> str: title = self.dataclass.__qualname__ if self.dest is not None: # Show name",
"self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError as e: # utils.default_value",
"child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal attribute field_wrapper = field_wrapper_class(field, parent=self,",
"Optional[str] = None, default: Union[Dataclass, Dict] = None, prefix: str = \"\", parent:",
"parent, which contains this child dataclass. self._field = _field # the default values",
"a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest}",
"group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str: return self._name @property def",
"option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options )",
"= None, default: Union[Dataclass, Dict] = None, prefix: str = \"\", parent: \"DataclassWrapper\"",
"field in self.fields if field.arg_options] if len(option_fields) > 0: # Only show groups",
"[] assert self.parent is not None if self.parent.defaults: self._defaults = [] for default",
"doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not None: if doc.docstring_below:",
"might fail # if the field has some required arguments logger.debug( f\"Could not",
"bool: return self._required @required.setter def required(self, value: bool): self._required = value for field",
"name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name",
"dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value] return self._defaults",
"field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type {field.type}, which",
"_MISSING_TYPE from logging import getLogger from typing import Dict, List, Optional, Type, Union,",
"self._defaults: return self._defaults if self._field is None: return [] assert self.parent is not",
"import dataclasses from dataclasses import _MISSING_TYPE from logging import getLogger from typing import",
"from .field_wrapper import FieldWrapper from .wrapper import Wrapper from .. import utils logger",
"List[DataclassWrapper] = [] self._parent = parent # the field of the parent, which",
"value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults",
"# handle a nested dataclass attribute dataclass, name = field.type, field.name child_wrapper =",
"not None: # Show name if exists title += f\" ['{self.dest}']\" return title",
"f\"Field {field.name} is of type {field.type}, which isn't \" f\"supported yet. (container of",
"default = None else: default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value =",
"@property def description(self) -> str: if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass,",
"in self.fields: field.required = value for child_wrapper in self._children: child_wrapper.required = value @property",
"[] self._parent = parent # the field of the parent, which contains this",
"f\"supported yet. (container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a",
"self.parent.dataclass, self._field.name ) if doc is not None: if doc.docstring_below: return doc.docstring_below elif",
"f\"wrapped field at {field_wrapper.dest} has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug(",
"= \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] =",
"field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass self._name =",
"@property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]: if",
"{field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has default values: {self.defaults}\"",
"if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc",
"field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required = False",
"Dict] = None, prefix: str = \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field",
"self.dataclass = dataclass self._name = name self.default = default self.prefix = prefix self.fields:",
"default: self.defaults = [default] self.optional: bool = False for field in dataclasses.fields(self.dataclass): if",
"required(self, value: bool): self._required = value for field in self.fields: field.required = value",
"self._required: bool = False self._explicit: bool = False self._dest: str = \"\" self._children:",
"if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type",
"groups with parameters group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields:",
"description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\"",
"= docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not None: if doc.docstring_below: return",
"the default values self._defaults: List[Dataclass] = [] if default: self.defaults = [default] self.optional:",
"a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass,",
"<reponame>eladrich/pyrallis<filename>pyrallis/wrappers/dataclass_wrapper.py<gh_stars>10-100 import argparse import dataclasses from dataclasses import _MISSING_TYPE from logging import getLogger",
"is of type {field.type}, which isn't \" f\"supported yet. (container of a dataclass",
"# if the field has some required arguments logger.debug( f\"Could not get default",
"self.fields: List[FieldWrapper] = [] self._required: bool = False self._explicit: bool = False self._dest:",
"[default] self.optional: bool = False for field in dataclasses.fields(self.dataclass): if not field.init: continue",
"# the default values self._defaults: List[Dataclass] = [] if default: self.defaults = [default]",
"NotImplementedError( f\"Field {field.name} is of type {field.type}, which isn't \" f\"supported yet. (container",
"-> List[Dataclass]: if self._defaults: return self._defaults if self._field is None: return [] assert",
"utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None )",
"self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value",
"utils.default_value tries to construct the field to get default value and might fail",
"DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name",
"\"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper",
"getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError as e: #",
"return self._defaults if self._field is None: return [] assert self.parent is not None",
"Dict, List, Optional, Type, Union, cast from pyrallis.utils import Dataclass from . import",
"self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required: bool = False self._explicit: bool",
"value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has default",
"self.dest is not None: # Show name if exists title += f\" ['{self.dest}']\"",
"field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a default value of",
"# Show name if exists title += f\" ['{self.dest}']\" return title @property def",
"value @property def title(self) -> str: title = self.dataclass.__qualname__ if self.dest is not",
"@property def title(self) -> str: title = self.dataclass.__qualname__ if self.dest is not None:",
"as e: # utils.default_value tries to construct the field to get default value",
"for field in self.fields: field.required = value for child_wrapper in self._children: child_wrapper.required =",
"elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type {field.type}, which isn't \"",
"= field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required =",
"import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name:",
"self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass,",
"parser) option_fields = [field for field in self.fields if field.arg_options] if len(option_fields) >",
"self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc looks",
"raise NotImplementedError( f\"Field {field.name} is of type {field.type}, which isn't \" f\"supported yet.",
"self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError as e: # utils.default_value tries",
"default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value]",
"self._name = name self.default = default self.prefix = prefix self.fields: List[FieldWrapper] = []",
"show groups with parameters group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in",
"parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ):",
"def required(self, value: bool): self._required = value for field in self.fields: field.required =",
"False child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal attribute field_wrapper = field_wrapper_class(field,",
"# Only show groups with parameters group = parser.add_argument_group( title=self.title, description=self.description ) for",
"in self.parent.defaults: if default is None: default = None else: default = getattr(default,",
"f\"The dataclass at attribute {self.dest} has default values: {self.defaults}\" ) def add_arguments(self, parser:",
") @property def name(self) -> str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]:",
"= [default] self.optional: bool = False for field in dataclasses.fields(self.dataclass): if not field.init:",
"self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value @property def title(self) ->",
"False for field in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError(",
"bool = False self._explicit: bool = False self._dest: str = \"\" self._children: List[DataclassWrapper]",
"@property def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if self._field is None:",
") def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser)",
"['{self.dest}']\" return title @property def description(self) -> str: if self.parent and self._field: doc",
"field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type):",
"import Wrapper from .. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__(",
"a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest}",
"child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass =",
"from . import docstring from .field_wrapper import FieldWrapper from .wrapper import Wrapper from",
"return [] assert self.parent is not None if self.parent.defaults: self._defaults = [] for",
"= False for field in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise",
"for child_wrapper in self._children: child_wrapper.required = value @property def descendants(self): for child in",
"field.arg_options] if len(option_fields) > 0: # Only show groups with parameters group =",
"@required.setter def required(self, value: bool): self._required = value for field in self.fields: field.required",
"for wrapped_field in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument(",
") if doc is not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return",
"= field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a default value",
"return self._required @required.setter def required(self, value: bool): self._required = value for field in",
"values self._defaults: List[Dataclass] = [] if default: self.defaults = [default] self.optional: bool =",
"= False child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal attribute field_wrapper =",
"elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass, name = field.type, field.name",
".field_wrapper import FieldWrapper from .wrapper import Wrapper from .. import utils logger =",
"assert self.parent is not None if self.parent.defaults: self._defaults = [] for default in",
"None, prefix: str = \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None,",
"default is None: default = None else: default = getattr(default, self.name) self._defaults.append(default) else:",
"parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg options for field",
"str = \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper]",
"= [] self._parent = parent # the field of the parent, which contains",
"if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc looks confusing, remove it",
"False self._dest: str = \"\" self._children: List[DataclassWrapper] = [] self._parent = parent #",
"doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc =",
"= utils.default_value(self._field) except TypeError as e: # utils.default_value tries to construct the field",
"is not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline:",
"[] self._required: bool = False self._explicit: bool = False self._dest: str = \"\"",
"default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser",
"attribute dataclass, name = field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field",
"self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not None: if",
"dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict] = None, prefix: str",
"name self.default = default self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required: bool",
"super().__init__(dataclass, name) self.dataclass = dataclass self._name = name self.default = default self.prefix =",
"of the parent, which contains this child dataclass. self._field = _field # the",
"return self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if self._field",
"\"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): #",
"str: title = self.dataclass.__qualname__ if self.dest is not None: # Show name if",
"e: # utils.default_value tries to construct the field to get default value and",
"group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg options",
"Union[Dataclass, Dict] = None, prefix: str = \"\", parent: \"DataclassWrapper\" = None, _field:",
"from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field for field",
"self._defaults: List[Dataclass] = [] if default: self.defaults = [default] self.optional: bool = False",
"name: Optional[str] = None, default: Union[Dataclass, Dict] = None, prefix: str = \"\",",
"len(option_fields) > 0: # Only show groups with parameters group = parser.add_argument_group( title=self.title,",
"= default self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required: bool = False",
"parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else: #",
"has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute",
") group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str: return self._name @property",
"self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not",
"\"\" # The base dataclass doc looks confusing, remove it return class_doc @property",
"List[Dataclass] = [] if default: self.defaults = [default] self.optional: bool = False for",
"confusing, remove it return class_doc @property def required(self) -> bool: return self._required @required.setter",
"dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper)",
"else: default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except TypeError",
"default value and might fail # if the field has some required arguments",
"name if exists title += f\" ['{self.dest}']\" return title @property def description(self) ->",
"name = field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required",
"return \"\" # The base dataclass doc looks confusing, remove it return class_doc",
"Union, cast from pyrallis.utils import Dataclass from . import docstring from .field_wrapper import",
"Dataclass from . import docstring from .field_wrapper import FieldWrapper from .wrapper import Wrapper",
"self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]:",
"if self.parent.defaults: self._defaults = [] for default in self.parent.defaults: if default is None:",
"default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has",
"= None, _field: dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass,",
"= field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif",
"= self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc",
"field to get default value and might fail # if the field has",
"**wrapped_field.arg_options ) @property def name(self) -> str: return self._name @property def parent(self) ->",
"= True self._children.append(child_wrapper) else: # a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix)",
"# the field of the parent, which contains this child dataclass. self._field =",
"dataclass self._name = name self.default = default self.prefix = prefix self.fields: List[FieldWrapper] =",
"dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass, name = field.type, field.name child_wrapper",
"name = field.type, field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper)",
"handle a nested dataclass attribute dataclass, name = field.type, field.name child_wrapper = DataclassWrapper(",
"with parameters group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug(",
"default: Union[Dataclass, Dict] = None, prefix: str = \"\", parent: \"DataclassWrapper\" = None,",
"\"\" self._children: List[DataclassWrapper] = [] self._parent = parent # the field of the",
"dataclass, name, parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name =",
"self._dest: str = \"\" self._children: List[DataclassWrapper] = [] self._parent = parent # the",
"parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a default value of {field_wrapper.default}\"",
"= utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None",
"self.dataclass.__qualname__ if self.dest is not None: # Show name if exists title +=",
"= _field # the default values self._defaults: List[Dataclass] = [] if default: self.defaults",
"'{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str: return",
"{self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser,",
"dataclasses import _MISSING_TYPE from logging import getLogger from typing import Dict, List, Optional,",
"field in self.fields: field.required = value for child_wrapper in self._children: child_wrapper.required = value",
"= DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional =",
"argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field for",
"f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def",
"0: # Only show groups with parameters group = parser.add_argument_group( title=self.title, description=self.description )",
"False self._explicit: bool = False self._dest: str = \"\" self._children: List[DataclassWrapper] = []",
") self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has default values: {self.defaults}\" )",
"docstring from .field_wrapper import FieldWrapper from .wrapper import Wrapper from .. import utils",
"except TypeError as e: # utils.default_value tries to construct the field to get",
"get default value and might fail # if the field has some required",
"class_doc @property def required(self) -> bool: return self._required @required.setter def required(self, value: bool):",
"import docstring from .field_wrapper import FieldWrapper from .wrapper import Wrapper from .. import",
"nested dataclass attribute dataclass, name = field.type, field.name child_wrapper = DataclassWrapper( dataclass, name,",
"return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) ->",
"utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self,",
"= [default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value @property",
"@property def required(self) -> bool: return self._required @required.setter def required(self, value: bool): self._required",
"a nested dataclass attribute dataclass, name = field.type, field.name child_wrapper = DataclassWrapper( dataclass,",
"self._field is None: return [] assert self.parent is not None if self.parent.defaults: self._defaults",
"-> str: if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if",
"= [] else: self._defaults = [default_field_value] return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]):",
"default values self._defaults: List[Dataclass] = [] if default: self.defaults = [default] self.optional: bool",
"utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type {field.type}, which isn't \" f\"supported",
"def title(self) -> str: title = self.dataclass.__qualname__ if self.dest is not None: #",
"-> str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def",
"'{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else:",
"dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of",
"defaults(self, value: List[Dataclass]): self._defaults = value @property def title(self) -> str: title =",
"to construct the field to get default value and might fail # if",
"FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass self._name = name self.default =",
"values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser parser =",
"dataclass at attribute {self.dest} has default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser):",
"getLogger from typing import Dict, List, Optional, Type, Union, cast from pyrallis.utils import",
"(container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): # handle a nested dataclass",
"in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is",
"base dataclass doc looks confusing, remove it return class_doc @property def required(self) ->",
"which isn't \" f\"supported yet. (container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type):",
"\"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc looks confusing, remove",
"self.default = default self.prefix = prefix self.fields: List[FieldWrapper] = [] self._required: bool =",
") self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper(",
"List[FieldWrapper] = [] self._required: bool = False self._explicit: bool = False self._dest: str",
"str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self)",
"class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass,",
"if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults = [default_field_value] return self._defaults @defaults.setter",
"options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self)",
"has default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from pyrallis.argparsing import ArgumentParser",
"return title @property def description(self) -> str: if self.parent and self._field: doc =",
"Only show groups with parameters group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field",
"dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field,",
"utils.default_value(self._field) except TypeError as e: # utils.default_value tries to construct the field to",
"doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or",
"value @property def descendants(self): for child in self._children: yield child yield from child.descendants",
"if field.arg_options] if len(option_fields) > 0: # Only show groups with parameters group",
"in self._children: child_wrapper.required = value @property def descendants(self): for child in self._children: yield",
"ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field for field in self.fields if",
"value: bool): self._required = value for field in self.fields: field.required = value for",
"child_wrapper = DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional",
"Wrapper from .. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self,",
"field has some required arguments logger.debug( f\"Could not get default value for field",
"import Dict, List, Optional, Type, Union, cast from pyrallis.utils import Dataclass from .",
"doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" #",
"pyrallis.argparsing import ArgumentParser parser = cast(ArgumentParser, parser) option_fields = [field for field in",
"at attribute {self.dest} has default values: {self.defaults}\" ) def add_arguments(self, parser: argparse.ArgumentParser): from",
"= value for field in self.fields: field.required = value for child_wrapper in self._children:",
"child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal attribute field_wrapper",
"parameters group = parser.add_argument_group( title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg",
"cast(ArgumentParser, parser) option_fields = [field for field in self.fields if field.arg_options] if len(option_fields)",
"return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('):",
"argparse import dataclasses from dataclasses import _MISSING_TYPE from logging import getLogger from typing",
"parent(self) -> Optional[\"DataclassWrapper\"]: return self._parent @property def defaults(self) -> List[Dataclass]: if self._defaults: return",
"self._defaults = value @property def title(self) -> str: title = self.dataclass.__qualname__ if self.dest",
"title += f\" ['{self.dest}']\" return title @property def description(self) -> str: if self.parent",
"= value @property def title(self) -> str: title = self.dataclass.__qualname__ if self.dest is",
"field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a default",
"= \"\" self._children: List[DataclassWrapper] = [] self._parent = parent # the field of",
"The base dataclass doc looks confusing, remove it return class_doc @property def required(self)",
"defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if self._field is None: return []",
"field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = []",
"the field of the parent, which contains this child dataclass. self._field = _field",
"# The base dataclass doc looks confusing, remove it return class_doc @property def",
"wrapped_field in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings,",
"import FieldWrapper from .wrapper import Wrapper from .. import utils logger = getLogger(__name__)",
"field of the parent, which contains this child dataclass. self._field = _field #",
"Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict] = None, prefix: str =",
"typing import Dict, List, Optional, Type, Union, cast from pyrallis.utils import Dataclass from",
"@property def name(self) -> str: return self._name @property def parent(self) -> Optional[\"DataclassWrapper\"]: return",
"field at {field_wrapper.dest} has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The",
"Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults = [] else: self._defaults",
"from .wrapper import Wrapper from .. import utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]):",
"dataclass doc looks confusing, remove it return class_doc @property def required(self) -> bool:",
"f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING",
"field.required = value for child_wrapper in self._children: child_wrapper.required = value @property def descendants(self):",
"DataclassWrapper( dataclass, name, parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional = True",
"import Dataclass from . import docstring from .field_wrapper import FieldWrapper from .wrapper import",
"type {field.type}, which isn't \" f\"supported yet. (container of a dataclass type)\" )",
"the field has some required arguments logger.debug( f\"Could not get default value for",
"Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass = dataclass self._name = name",
"child_wrapper in self._children: child_wrapper.required = value @property def descendants(self): for child in self._children:",
"from dataclasses import _MISSING_TYPE from logging import getLogger from typing import Dict, List,",
"tries to construct the field to get default value and might fail #",
"parent=self, _field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper",
"= self.dataclass.__qualname__ if self.dest is not None: # Show name if exists title",
"prefix: str = \"\", parent: \"DataclassWrapper\" = None, _field: dataclasses.Field = None, field_wrapper_class:",
"get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value,",
"if self._defaults: return self._defaults if self._field is None: return [] assert self.parent is",
"self._children: List[DataclassWrapper] = [] self._parent = parent # the field of the parent,",
"None else: default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value = utils.default_value(self._field) except",
"default=None ) child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal",
"self.parent is not None if self.parent.defaults: self._defaults = [] for default in self.parent.defaults:",
"f\" ['{self.dest}']\" return title @property def description(self) -> str: if self.parent and self._field:",
"= [] self._required: bool = False self._explicit: bool = False self._dest: str =",
"= getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str] = None,",
"title(self) -> str: title = self.dataclass.__qualname__ if self.dest is not None: # Show",
"parser = cast(ArgumentParser, parser) option_fields = [field for field in self.fields if field.arg_options]",
"title=self.title, description=self.description ) for wrapped_field in option_fields: logger.debug( f\"Arg options for field '{wrapped_field.name}':",
"List[Dataclass]): self._defaults = value @property def title(self) -> str: title = self.dataclass.__qualname__ if",
"): # super().__init__(dataclass, name) self.dataclass = dataclass self._name = name self.default = default",
"def description(self) -> str: if self.parent and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name",
"field '{wrapped_field.name}': {wrapped_field.arg_options}\" ) group.add_argument( *wrapped_field.option_strings, **wrapped_field.arg_options ) @property def name(self) -> str:",
"doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return",
"DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str] = None, default: Union[Dataclass, Dict]",
") elif dataclasses.is_dataclass(field.type): # handle a nested dataclass attribute dataclass, name = field.type,",
"bool = False for field in dataclasses.fields(self.dataclass): if not field.init: continue elif utils.is_tuple_or_list_of_dataclasses(field.type):",
"if default is None: default = None else: default = getattr(default, self.name) self._defaults.append(default)",
"prefix=self.prefix) logger.debug( f\"wrapped field at {field_wrapper.dest} has a default value of {field_wrapper.default}\" )",
"if self._field is None: return [] assert self.parent is not None if self.parent.defaults:",
". import docstring from .field_wrapper import FieldWrapper from .wrapper import Wrapper from ..",
") child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else: # a normal attribute",
"if doc is not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above",
"for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if isinstance(default_field_value, _MISSING_TYPE): self._defaults =",
"self._children.append(child_wrapper) else: # a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped",
"= cast(ArgumentParser, parser) option_fields = [field for field in self.fields if field.arg_options] if",
"# utils.default_value tries to construct the field to get default value and might",
"str = \"\" self._children: List[DataclassWrapper] = [] self._parent = parent # the field",
"self.fields if field.arg_options] if len(option_fields) > 0: # Only show groups with parameters",
"value and might fail # if the field has some required arguments logger.debug(",
"Optional, Type, Union, cast from pyrallis.utils import Dataclass from . import docstring from",
"name, parent=self, _field=field, default=None ) child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else:",
"= [] for default in self.parent.defaults: if default is None: default = None",
"continue elif utils.is_tuple_or_list_of_dataclasses(field.type): raise NotImplementedError( f\"Field {field.name} is of type {field.type}, which isn't",
"return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__",
"dataclasses.Field = None, field_wrapper_class: Type[FieldWrapper] = FieldWrapper ): # super().__init__(dataclass, name) self.dataclass =",
"elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper = DataclassWrapper( dataclass, name,",
"try: default_field_value = utils.default_value(self._field) except TypeError as e: # utils.default_value tries to construct",
"= [] if default: self.defaults = [default] self.optional: bool = False for field",
"and self._field: doc = docstring.get_attribute_docstring( self.parent.dataclass, self._field.name ) if doc is not None:",
"# a normal attribute field_wrapper = field_wrapper_class(field, parent=self, prefix=self.prefix) logger.debug( f\"wrapped field at",
"arguments logger.debug( f\"Could not get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value",
"for default in self.parent.defaults: if default is None: default = None else: default",
"self.fields.append(field_wrapper) logger.debug( f\"The dataclass at attribute {self.dest} has default values: {self.defaults}\" ) def",
"isn't \" f\"supported yet. (container of a dataclass type)\" ) elif dataclasses.is_dataclass(field.type): #",
"return self._defaults @defaults.setter def defaults(self, value: List[Dataclass]): self._defaults = value @property def title(self)",
"doc is not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif",
"[] if default: self.defaults = [default] self.optional: bool = False for field in",
"_field=field ) self._children.append(child_wrapper) elif utils.contains_dataclass_type_arg(field.type): dataclass = utils.get_dataclass_type_arg(field.type) name = field.name child_wrapper =",
"_field=field, default=None ) child_wrapper.required = False child_wrapper.optional = True self._children.append(child_wrapper) else: # a",
"at {field_wrapper.dest} has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper) logger.debug( f\"The dataclass",
"doc.comment_above: return doc.comment_above elif doc.comment_inline: return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if",
"def defaults(self) -> List[Dataclass]: if self._defaults: return self._defaults if self._field is None: return",
"logger.debug( f\"wrapped field at {field_wrapper.dest} has a default value of {field_wrapper.default}\" ) self.fields.append(field_wrapper)",
"{field.name} is of type {field.type}, which isn't \" f\"supported yet. (container of a",
"None: default = None else: default = getattr(default, self.name) self._defaults.append(default) else: try: default_field_value",
"return doc.comment_inline class_doc = self.dataclass.__doc__ or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The",
"Type, Union, cast from pyrallis.utils import Dataclass from . import docstring from .field_wrapper",
"utils logger = getLogger(__name__) class DataclassWrapper(Wrapper[Dataclass]): def __init__( self, dataclass: Type[Dataclass], name: Optional[str]",
"dataclasses from dataclasses import _MISSING_TYPE from logging import getLogger from typing import Dict,",
"fail # if the field has some required arguments logger.debug( f\"Could not get",
"or \"\" if class_doc.startswith(f'{self.dataclass.__name__}('): return \"\" # The base dataclass doc looks confusing,",
"import argparse import dataclasses from dataclasses import _MISSING_TYPE from logging import getLogger from",
"child_wrapper.required = value @property def descendants(self): for child in self._children: yield child yield",
"not get default value for field '{self._field.name}'\\n\\tUnderlying Error: {e}\") default_field_value = dataclasses.MISSING if",
"prefix self.fields: List[FieldWrapper] = [] self._required: bool = False self._explicit: bool = False",
"not None: if doc.docstring_below: return doc.docstring_below elif doc.comment_above: return doc.comment_above elif doc.comment_inline: return",
"None: return [] assert self.parent is not None if self.parent.defaults: self._defaults = []"
] |
[
"mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True:",
"savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised",
"print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True:",
"mean, \"SD: \", standard_dev, \"Median: \", median print \"mean2: \", mean2, \"SD2: \",",
"ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised",
"savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show()",
"Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2)",
"== True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050')",
"hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i in hist_values5] # Double",
"Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if",
"plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max",
"plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05),",
"Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0,",
"for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices):",
"np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3,",
"ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised",
"standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \",",
"\", median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 #",
"area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i <",
"Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified3.pdf') plt.show() ######################################## print",
"plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max =",
"prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i])",
"x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[]",
"plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if",
"if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf')",
"2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1)",
"sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator =",
"@author: Jordan \"\"\" # The following plots several figures from the MCMC. Not",
"Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if",
"ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$')",
"= SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report()",
"ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF')",
"result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0",
"P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2)",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Nov 15 21:12:41 2017",
"the code has been kept in this single file # for simplicity. print",
"include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None)",
"P_full=full P_total=tot if verbose==True: print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices)",
"plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1,",
"plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3,",
"/ 2 xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals,",
"in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False)",
"color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2),",
"sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot,",
"not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if",
"relevant, but the code has been kept in this single file # for",
"if verbose==True: print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices)",
"Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount",
"ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",",
"Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100)",
"plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number",
"of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples')",
"yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1,",
"= f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f:",
"mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean,",
"position for probability=({}) not correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m')",
"savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0],",
"if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and",
"hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4))",
"figures from the MCMC. Not all are relevant, but the code has been",
"Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total",
"for i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i])",
"newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \",",
"names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2",
"b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist",
"names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt',",
"ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b',",
"ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c',",
"print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 # Defines the",
"ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$')",
"testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1])",
"= mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2))",
"median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 # Defines",
"axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\")",
"if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True,",
"inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False)",
"label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0,",
"if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration')",
"plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes",
"range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1)",
"plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent",
"plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi",
"ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1,",
"\"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf')",
"\", median print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print",
"== True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE",
"Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$')",
"(found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding",
"ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap,",
"xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')",
"Double Ttot and Tfull as only half values were used in the MCMC",
"\"Start...\" # Import modules import numpy as np import matplotlib.pyplot as plt from",
"plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration",
"SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals,",
"\", mean, \"SD: \", standard_dev, \"Median: \", median print \"mean2: \", mean2, \"SD2:",
"False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if",
"b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures ==",
"plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05),",
"plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR:",
"origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total",
"color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2),",
"plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05),",
"3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint",
"label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0,",
"specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD",
"INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1]",
"Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0",
"ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf')",
"standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev, \"Median: \",",
"= 0 for i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux =",
"following plots several figures from the MCMC. Not all are relevant, but the",
"plots several figures from the MCMC. Not all are relevant, but the code",
"PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised",
"savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show()",
"n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures",
"21:12:41 2017 @author: Jordan \"\"\" # The following plots several figures from the",
"ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase",
"origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint",
"plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of",
"plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3)",
"if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0]",
"Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared')",
"plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF')",
"SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results",
"Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05),",
"with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 =",
"as np import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as",
"2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False)",
"fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False)",
"Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial,",
"Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True:",
"color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2),",
"True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print",
"ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf')",
"has been kept in this single file # for simplicity. print \"Start...\" #",
"standard_dev3, \"Median3: \", median3 # Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid",
"(ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 =",
"\"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 # Defines the model",
"# Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True:",
"ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off')",
"label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if",
"== True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase",
"### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05),",
"color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3),",
"ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b',",
"PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\",",
"point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \",",
"ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf')",
"print \"mean: \", mean, \"SD: \", standard_dev, \"Median: \", median print \"mean2: \",",
"if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent =",
"if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent =",
"y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g',",
"for simplicity. print \"Start...\" # Import modules import numpy as np import matplotlib.pyplot",
"label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist,",
"plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight')",
"= False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc]",
"xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig,",
"cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3])",
"maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None)",
"ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint",
"x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0",
"Ttot and Tfull as only half values were used in the MCMC (to",
"code has been kept in this single file # for simplicity. print \"Start...\"",
"True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL",
"plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else:",
"2 xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals)",
"# The following plots several figures from the MCMC. Not all are relevant,",
"and Tfull as only half values were used in the MCMC (to simplify",
"plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist",
"values were used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if",
"cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase",
"with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 =",
"label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full",
"The following plots several figures from the MCMC. Not all are relevant, but",
"plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in",
"#myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3))",
"plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist",
"Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared')",
"open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines()",
"savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5)",
"MCMC results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f:",
"ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist =",
"E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding",
"in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i in hist_values5] #",
"if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \",",
"= plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf')",
"(total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2)",
"found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050')",
"summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print",
"prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1)",
"Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve",
"uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase')",
"maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0]",
"found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050')",
"plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0],",
"xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result",
"\"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3,",
"plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator)",
"chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True,",
"(to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt',",
"sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5)",
"print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print",
"= plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf')",
"orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised",
"plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05),",
"newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower:",
"heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]",
"ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3))",
"inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False)",
"open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines()",
"= np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2),",
"num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i",
"cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint",
"ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration')",
"plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0,",
"file # for simplicity. print \"Start...\" # Import modules import numpy as np",
"= inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight')",
"= plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\")",
"on Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\" # The following plots",
"extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off')",
"heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]",
"Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if",
"break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1])",
"for probability=({}) not correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if",
"ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2,",
"ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True:",
"result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print",
"several figures from the MCMC. Not all are relevant, but the code has",
"= plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\",",
"plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05),",
"ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3,",
"Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$')",
"model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print",
"PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint",
"and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1)) found =",
"[xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col',",
"ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1))",
"SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] +",
"Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent",
"height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\")",
"sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges",
"= np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2),",
"median print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3:",
"ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$')",
"Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show()",
"plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True:",
"plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0,",
"Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared')",
"plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True:",
"2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator)",
"plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max",
"plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\",",
"#ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True:",
"= np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2),",
"xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig,",
"ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show()",
"xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig,",
"cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",",
"fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.)",
"position for probability=({}) not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break",
"plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges",
"#SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print",
"maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\",",
"if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised",
"plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max =",
"Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase')",
"hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4))",
"yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1,",
"plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean')",
"i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux)",
"print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area",
"f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for",
"(ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\")",
"yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T,",
"position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1)",
"plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05),",
"if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i",
"E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k')",
"if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples')",
"len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)): loc=len(xvals)-1-j",
"plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break",
"True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05))",
"Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared')",
"ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent",
"plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number",
"== True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050')",
"ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges",
"color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist,",
"standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \",",
"P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2)",
"plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges",
"plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print",
"delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb",
"i in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i in hist_values4]",
"plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b')",
"\", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show()",
"plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200)",
"CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center =",
"if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent =",
"True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({})",
"cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator",
"plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent",
"plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if",
"np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ###",
"width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator",
"lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import",
"b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals = bin_center,",
"#ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2))",
"patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True:",
"break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1))",
"modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import",
"model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print",
"mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 # Defines the model generation function",
"prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({}) not found.",
"ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show()",
"ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition",
"plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True)",
"i in hist_values5] # Double Ttot and Tfull as only half values were",
"mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev,",
"extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,",
"print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3: \",",
"= model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for",
"plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3),",
"plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3,",
"Created on Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\" # The following",
"#Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print",
"\"Median2: \", median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3",
"for probability=({}) not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2))",
"label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint",
"plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase')",
"= model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode",
"ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m',",
"Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05),",
"True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05))",
"names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point",
"= mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared",
"ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b',",
"plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0,",
"savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared",
"= mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if",
"ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"(position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1)) found = True",
"plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0,",
"label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0,",
"contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")",
"if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent =",
"results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2",
"as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i",
"plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0],",
"in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit,",
"testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper:",
"\", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3, \"SD3:",
"np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3,",
"i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full",
"myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1))",
"newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found =",
"if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf')",
"Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5)",
"hist_values5] # Double Ttot and Tfull as only half values were used in",
"ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m',",
"the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details:",
"\", median3 # Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot",
"plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF')",
"i in hist_values4] hist_values5=[float(i) for i in hist_values5] # Double Ttot and Tfull",
"contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00)",
"= np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights,",
"prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({}) not",
"color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist,",
"if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r')",
"PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges =",
"median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev, \"Median:",
"ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m',",
"if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf')",
"PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5,",
"modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model",
"plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase",
"range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and",
"ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared",
"hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as",
"plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max",
"savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show()",
"hist_values5=[float(i) for i in hist_values5] # Double Ttot and Tfull as only half",
"i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin')",
"if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0]",
"ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised",
"patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights",
"savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ###",
"plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True:",
"summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array",
"plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show()",
"plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap,",
"plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR:",
"f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt')",
"from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes #",
"E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r')",
"orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF')",
"np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3,",
"ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$')",
"only half values were used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2",
"contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00)",
"Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if",
"\"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0",
"if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True:",
"######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders)",
"Tfull as only half values were used in the MCMC (to simplify maths)",
"Not all are relevant, but the code has been kept in this single",
"#Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None)",
"delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None)",
"ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared",
"plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200)",
"plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max =",
"in hist_values4] hist_values5=[float(i) for i in hist_values5] # Double Ttot and Tfull as",
"plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else:",
"summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals):",
"model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) #",
"= bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals,",
"print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if",
"Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0,",
"y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g',",
"plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1],",
"PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges =",
"ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration')",
"plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1],",
"ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position')",
"bin_borders, _ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2",
"the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False:",
"if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r')",
"sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator",
"ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c',",
"\"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True:",
"print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[]",
"Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist ==",
"np import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker",
"#modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices",
"\"SD: \", standard_dev, \"Median: \", median print \"mean2: \", mean2, \"SD2: \", standard_dev2,",
"Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced",
"\", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show()",
"plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position')",
"Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False",
"\", standard_dev3, \"Median3: \", median3 # Defines the model generation function def generate_model(full,tot,mid,verbose):",
"\"Median3: \", median3 # Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full",
"of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges =",
"ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent",
"for i in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i in",
"graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per",
"bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration",
"inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\")",
"as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import",
"= n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals",
"ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF')",
"myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1))",
"mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with open('hist_values1.txt') as f: hist_values1 =",
"f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5",
"Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0,",
"b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures ==",
"axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\")",
"savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint",
"ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf')",
"correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False:",
"per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean:",
"standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev, \"Median: \", median print \"mean2:",
"f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i in",
"standard_dev, \"Median: \", median print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \",",
"plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break",
"plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3,",
"Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified3.pdf') plt.show()",
"plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0,",
"summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print",
"newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False",
"print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1])",
"loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003)",
"== True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE",
"origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2,",
"ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf')",
"\"mean: \", mean, \"SD: \", standard_dev, \"Median: \", median print \"mean2: \", mean2,",
"x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)):",
"in this single file # for simplicity. print \"Start...\" # Import modules import",
"names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None)",
"been kept in this single file # for simplicity. print \"Start...\" # Import",
"matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator",
"bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) =",
"Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3,",
"if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05))",
"ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show()",
"bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) /",
"plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show()",
"Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared')",
"uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0:",
"plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0],",
"and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise",
"if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5)",
"f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1]",
"P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount",
"np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[]",
"\", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf')",
"and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({})",
"plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean')",
"for i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i])",
"plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist",
"if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and",
"ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf')",
"j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if found",
"plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0],",
"True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print",
"= np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux =",
"ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised",
"as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i)",
"== n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _",
"extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator)",
"fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower',",
"if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k')",
"hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True,",
"plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r',",
"plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True:",
"savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show()",
"mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if",
"= bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights model =",
"Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if",
"Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin')",
"\", standard_dev, \"Median: \", median print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2:",
"plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for",
"n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ =",
"bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals)",
"### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05),",
"ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$')",
"0 for i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star)",
"color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\")",
"plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number",
"probability=({}) not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2)",
"Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05),",
"total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux",
"hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i in hist_values2]",
"hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4))",
"testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1])",
"# Double Ttot and Tfull as only half values were used in the",
"Import MCMC results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as",
"savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised",
"total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for",
"np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures ==",
"mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev, \"Median: \", median",
"ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if",
"uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0",
"found = False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\")",
"\", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures",
"position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)): loc=len(xvals)-1-j if",
"in hist_values5] # Double Ttot and Tfull as only half values were used",
"plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3),",
"extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator)",
"= mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5))",
"found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position",
"utf-8 -*- \"\"\" Created on Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\"",
"matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with open('hist_values1.txt')",
"i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1)",
"of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples')",
"Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position')",
"median3 # Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if",
"if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf')",
"axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3)",
"plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05),",
"in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i)",
"plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2,",
"interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf')",
"#myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised",
"num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices):",
"\"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3,",
"raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if found == True: newx2.append(xvals[loc])",
"testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1])",
"testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase')",
"ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist =",
"uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for",
"Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges,",
"total_amount = 0 for i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux",
"coding: utf-8 -*- \"\"\" Created on Wed Nov 15 21:12:41 2017 @author: Jordan",
"i in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i in hist_values3]",
"print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist,",
"label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total",
"#!/usr/bin/env python2 # -*- coding: utf-8 -*- \"\"\" Created on Wed Nov 15",
"names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph",
"but the code has been kept in this single file # for simplicity.",
"\"\"\" # The following plots several figures from the MCMC. Not all are",
"delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications",
"maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\",",
"\"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf')",
"plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0,",
"savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ###",
"hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for",
"xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3)",
"(xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for",
"sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator =",
"ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full",
"break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1])",
"savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean),",
"break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1])",
"open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines()",
"plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges =",
"plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True:",
"<reponame>jlindsey1/MappingExoplanets<filename>MCMC_plotting.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- \"\"\" Created on Wed Nov",
"# Import modules import numpy as np import matplotlib.pyplot as plt from lmfit.models",
"plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator)",
"P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2)",
"if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if",
"for i in hist_values5] # Double Ttot and Tfull as only half values",
"= f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in",
"in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if",
"\", standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3, \"SD3: \", standard_dev3, \"Median3:",
"heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]",
"plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full",
"Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if",
"color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\")",
"ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised",
"plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1],",
"yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent,",
"# Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial",
"savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0],",
"plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if",
"savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf')",
"plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of",
"label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist,",
"sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1,",
"yvals = bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result =",
"newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower:",
"ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value')",
"plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR:",
"i in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i in hist_values5]",
"ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True)",
"rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount =",
"bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase",
"< len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)):",
"if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent =",
"plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2,",
"Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc])",
"== True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF')",
"\"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if",
"xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show()",
"ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration')",
"(position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not",
"plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration",
"height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator =",
"yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1,",
"+ np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel() params",
"ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner2.pdf') plt.show() y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]",
"with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 =",
"plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05),",
"\"Median: \", median print \"mean2: \", mean2, \"SD2: \", standard_dev2, \"Median2: \", median2",
"testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of",
"(total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount =",
"hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as",
"newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1:",
"savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised",
"the MCMC. Not all are relevant, but the code has been kept in",
"import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker as mticker from",
"= f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f:",
"Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if",
"for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1)",
"== True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF')",
"from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with open('hist_values1.txt') as f: hist_values1",
"# Import MCMC results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt')",
"i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area =",
"label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if",
"== True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE",
"hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for",
"simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True,",
"newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for",
"savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf')",
"were used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True:",
"plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total",
"hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt',",
"modules import numpy as np import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel",
"color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\")",
"bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights model",
"ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$')",
"plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount -",
"if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \",",
"np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel() params =",
"plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist",
"for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area",
"uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$')",
"Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges,",
"print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration",
"for i in hist_values4] hist_values5=[float(i) for i in hist_values5] # Double Ttot and",
"PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2),",
"Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True)",
"ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF')",
"ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified3.pdf')",
"PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\",",
"color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend()",
"if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges,",
"orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration')",
"ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if",
"area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9]",
"\"SD3: \", standard_dev3, \"Median3: \", median3 # Defines the model generation function def",
"else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2))",
"plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05),",
"raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >=",
"modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i])",
"stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount",
"cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration",
"kept in this single file # for simplicity. print \"Start...\" # Import modules",
"testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper:",
"orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator =",
"mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF') ax4.set_xlabel('Marginalised Chi-Squared PDF')",
"color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend()",
"in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y)",
"- modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)):",
"else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max())",
"plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show()",
"ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges",
"loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight')",
"newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower:",
"from the MCMC. Not all are relevant, but the code has been kept",
"Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$')",
"\", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if",
"plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 print",
"savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show()",
"orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF')",
"orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF')",
"else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin')",
"Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max())",
"maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx",
"= f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f:",
"uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1]",
"mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if",
"result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i]",
"plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist",
"plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap,",
"origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\")",
"= inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight')",
"bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ########################################",
"newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise",
"plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05),",
"plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of",
"#myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2))",
"Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1,",
"used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1'",
"Defines the model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print",
"plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2),",
"plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3)",
"color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2),",
"modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y",
"\"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while",
"if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0]",
"yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1,",
"= plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp2.pdf')",
"if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration')",
"= mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5))",
"hist_values4] hist_values5=[float(i) for i in hist_values5] # Double Ttot and Tfull as only",
"np.abs(maxvalx-newx2[-1]) break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ###",
"n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures",
"model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i",
"bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals = bin_center, bin_heights model = SkewedGaussianModel()",
"ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap,",
"cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",",
"def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \", Initial, P_full, P_total,",
"loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1])",
"loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2",
"if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position')",
"#ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf')",
"uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values']))",
"(ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\")",
"plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True:",
"Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase",
"savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0],",
"#plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1))",
"= total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0)",
"np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3,",
"P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1)",
"all are relevant, but the code has been kept in this single file",
"bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration",
"np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star)",
"graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6",
"Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max())",
"### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist, patches_hist bin_center",
"plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if",
"plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1",
"sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator",
"height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator =",
"error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if",
"ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF')",
"ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True:",
"hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i",
"break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ###",
"plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1],",
"ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1",
"contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#,",
"model generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \",",
"of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples')",
"15 21:12:41 2017 @author: Jordan \"\"\" # The following plots several figures from",
"= total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i",
"as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with",
"Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show()",
"_ = n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals,",
"bin_center, bin_heights model = SkewedGaussianModel() params = model.guess(yvals, x=xvals) result = model.fit(yvals, params,",
"plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1],",
"verbose==True: print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1])",
"#plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total",
"orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF')",
"extent=extent, origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1,",
"inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt',",
"summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print",
"orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position')",
"result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval:",
"params = model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2)",
"\"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference))",
"if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1))",
"and found==False: raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if found ==",
"bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration",
"b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures ==",
"found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise",
"xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig,",
"range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True:",
"ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist, patches_hist =",
"bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges =",
"Nov 15 21:12:41 2017 @author: Jordan \"\"\" # The following plots several figures",
"simplicity. print \"Start...\" # Import modules import numpy as np import matplotlib.pyplot as",
"if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf')",
"=\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i",
"True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print",
"= np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0",
"ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Total",
"heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]",
"ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$')",
"True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL",
"params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in",
"plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist == n_hist.max()) print",
"plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else:",
"2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False)",
"plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() heatmap, xedges,",
"include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None)",
"import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with",
"hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i in hist_values5] # Double Ttot",
"plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase')",
"patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True:",
"label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0,",
"numpy as np import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import matplotlib.ticker",
"plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True:",
"PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean3), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean3-standard_dev3), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2),",
"names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True,",
"open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for",
"plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist4.pdf') plt.show() plt.hist2d(hist_values5,hist_values3,",
"= plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\")",
"import SkewedGaussianModel import matplotlib.ticker as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC",
"plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200)",
"and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position",
"origin='lower', cmap='Greys') axins1 = inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\")",
"== True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050')",
"plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True:",
"return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if",
"plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation",
"print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures ==",
"Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]):",
"width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",",
"Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase')",
"print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1) median=np.median(hist_values1) standard_dev=np.std(hist_values1)",
"uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53)",
"n_hist, b_hist, patches_hist bin_center = bin_borders[:-1] + np.diff(bin_borders) / 2 xvals, yvals =",
"width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator",
"((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys')",
"for i in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i in",
"\"\"\" Created on Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\" # The",
"hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i",
"range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#,",
"-*- \"\"\" Created on Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\" #",
"= f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i)",
"total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue)",
"= [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,",
"xedges, yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig,",
"if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full Duration Phase') if savefigures==True:",
"MCMC. Not all are relevant, but the code has been kept in this",
"in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i)",
"print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number",
"in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices): total_amount =",
"Wed Nov 15 21:12:41 2017 @author: Jordan \"\"\" # The following plots several",
"plt.show() plt.hist2d(hist_values5,hist_values3, bins=200) plt.xlabel('Full Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges,",
"ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared PDF')",
"plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break",
"plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean')",
"Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[]",
"(position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1)) found",
"as only half values were used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2",
"maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none')",
"ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position') ax3.set_ylabel('Chi-Squared Value')",
"ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified3.pdf') plt.show() ######################################## print \"Done.\"",
"plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0],",
"generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \", Initial, P_full, P_total, Length",
"ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('Marginalised Chi-Squared",
"import numpy as np import matplotlib.pyplot as plt from lmfit.models import SkewedGaussianModel import",
"median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD: \", standard_dev, \"Median: \", median print",
"for i in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i in",
"i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j in",
"np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show()",
"this single file # for simplicity. print \"Start...\" # Import modules import numpy",
"testcondition if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase')",
"ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True)",
"delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2",
"plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint",
"if savefigures==True: plt.savefig('parameter-variation1.pdf') plt.show() plt.scatter(xpoints2,hist_values2,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Total Duration Phase') if savefigures==True:",
"y,x,_=plt.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=Initial_initial,c='k',lw=2,label='Origin') plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g',",
"if savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised",
"testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper:",
"= (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount",
"Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist ==",
"hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i",
"f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as f: hist_values4",
"plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder: maxval=0 maxvalx=0 for i in range(len(xvals)): if result.best_fit[i]>maxval: maxval=result.best_fit[i]",
"ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF2-modified.pdf') plt.show()",
"plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation",
"P_total=tot if verbose==True: print \"Details: \", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial,",
"plt.xlabel('Midpoint Phase Position') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev),",
"f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt')",
"+ modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return",
"plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r',",
"label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0,",
"loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00)",
"ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF')",
"\", mean3, \"SD3: \", standard_dev3, \"Median3: \", median3 # Defines the model generation",
"Samples') plt.ylabel('Total Duration Phase') if savefigures==True: plt.savefig('parameter-variation2.pdf') plt.show() plt.scatter(xpoints2,hist_values5,c='b',s=3) plt.xlabel('Number of Samples') plt.ylabel('Full",
"python2 # -*- coding: utf-8 -*- \"\"\" Created on Wed Nov 15 21:12:41",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Nov 15 21:12:41 2017 @author:",
"n_hist, b_hist, patches_hist = plt.hist(hist_values5,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values5,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures",
"total_amount - modeldata1['bin_values'][i] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange[i]) uniform_curve_y.append(fractional_flux) if include_middle==True: for i in",
"patches_hist = plt.hist(hist_values1,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values1,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Midpoint Phase Position') plt.ylabel('Normalised PDF') if savefigures == True:",
"model.guess(yvals, x=xvals) result = model.fit(yvals, params, x=xvals) print result.fit_report() plt.plot(xvals, result.best_fit,c='c',lw=2) #Mode Finder:",
"if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform",
"np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders,",
"inset_axes # Import MCMC results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with",
"Phase Position') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist ==",
"probability=({}) not correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist)",
"include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model",
"ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean3-standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean3+standard_dev3), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$')",
"j in range(len(xvals)): loc=len(xvals)-1-j if loc==-1: raise Exception(\"Array error.\") position2=result.best_fit[loc] if (position2>=position1) and",
"not correctly found. E1\".format(position1)) found = True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and",
"(position2>=position1) and (found==False) and (xvals[loc]<=prev_highest_position[-1]) and (position2 >= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0):",
"print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_full_initial,c='k',lw=2,label='Origin') plt.xlabel('Full Duration",
"### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position') if savefigures==True: plt.savefig('parameter-variation1.pdf')",
"ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration') ax3.set_ylabel('Full",
"median=np.median(hist_values1) standard_dev=np.std(hist_values1) mean2=np.mean(hist_values2) median2=np.median(hist_values2) standard_dev2=np.std(hist_values2) mean3=np.mean(hist_values5) median3=np.median(hist_values5) standard_dev3=np.std(hist_values5) print \"mean: \", mean, \"SD:",
"yedges = np.histogram2d(hist_values1, hist_values2, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1,",
"savefigures == True: plt.savefig('asymmetric1.pdf') plt.show() ### y,x,_=plt.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.axvline(x=P_total_initial,c='k',lw=2,label='Origin') plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared",
"summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i]",
"plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist2.pdf') plt.show() plt.hist2d(hist_values1,hist_values3,",
"as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with",
"uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if",
"plt.hist2d(hist_values1,hist_values3, bins=200) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total",
"with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i)",
"label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if",
"savefigures==True: plt.savefig('parameter-variation3.pdf') plt.show() plt.scatter(xpoints2,hist_values4,c='m',s=3) plt.xlabel('Number of Samples') plt.ylabel('Reduced Chi Squared') if savefigures==True: plt.savefig('parameter-variation3.pdf')",
"np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2), (ax3,",
"Phase Position') ax3.set_ylabel('Chi-Squared Value') ax1.set_ylabel('PDF') ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3,",
"savefigures==True: plt.savefig('corner-modified2.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values5, bins=(100,100),normed=True) extent = [xedges[0],",
"Jordan \"\"\" # The following plots several figures from the MCMC. Not all",
"Position') ax3.set_ylabel('Total Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show()",
"f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3",
"f.read().splitlines() hist_values1=[float(i) for i in hist_values1] hist_values2=[float(i) for i in hist_values2] hist_values3=[float(i) for",
"\", Initial, P_full, P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed)",
"True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3) plt.xlabel('Number of Samples') plt.ylabel('Midpoint Phase Position')",
"2017 @author: Jordan \"\"\" # The following plots several figures from the MCMC.",
"half values were used in the MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True",
"ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",",
">= prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly",
"savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ###",
"savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0],",
"while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found = False for j",
"raise Exception(\"Corresponding position for probability=({}) not correctly found. E1\".format(position1)) found = True prev_highest.append(position2)",
"with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines() with open('hist_values2.txt') as f: hist_values2 =",
"range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices): total_amount = total_amount",
"delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices'] print P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices P_total_initial=P_total*2 P_full_initial=P_full*2 Initial_initial=Initial savefigures=False sigma_value=35*1e-6 #SD per point mean=np.mean(hist_values1)",
"plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print",
"plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r',",
"ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True:",
"plt.xlabel('Full Occultation Duration') plt.ylabel('Normalised PDF') if savefigures == True: plt.savefig('plottemp3.pdf') bin_max = np.where(n_hist",
"prev_highest[-1]): if (position2>1e3*position1) and (position1!=0): raise Exception(\"Corresponding position for probability=({}) not correctly found.",
"delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt', names=True, delimiter=';',dtype=None) #modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True,",
"inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid' chi2file=np.genfromtxt(str(inputfile)+'.txt', names=True, delimiter=';',dtype=None) modeldata1=np.genfromtxt('uniformingress1.txt', names=True, delimiter=';',dtype=None) #Uniform model modeldata2=np.genfromtxt('uniformegress1.txt',",
"\"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition",
"newx1=[] newy1=[] newx2=[] newy2=[] while i < len(xvals): position1=result.best_fit[i] newx1.append(xvals[i]) newy1.append(position1) summation1=np.trapz(newy1,x=newx1) found",
"uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values']) for i in range(Nslices): total_amount = total_amount - modeldata1['bin_values'][i]",
"#modeldata1=np.genfromtxt('nolimbingress1.txt', names=True, delimiter=';',dtype=None) #No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt',",
"single file # for simplicity. print \"Start...\" # Import modules import numpy as",
"mean2, \"SD2: \", standard_dev2, \"Median2: \", median2 print \"mean3: \", mean3, \"SD3: \",",
"import inset_axes # Import MCMC results with open('hist_values1.txt') as f: hist_values1 = f.read().splitlines()",
"total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue)",
"Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist3.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=200) plt.xlabel('Total Duration Phase') plt.ylabel('Chi-Squared') if",
"plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False)",
"label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF1-modified.pdf') plt.show() n_hist, b_hist,",
"ax4.set_xlabel('PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values3)*0.95,np.max(hist_values3)) if savefigures==True: plt.savefig('chisquared-corner1.pdf') plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared')",
"found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(Initial_initial,c='r') plt.axvline(maxvalx,c='k') plt.axvline(newx1[-1],c='#505050')",
"f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt')",
"generation function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \", Initial,",
"= (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux) maxvalue=np.max(uniform_curve_y) uniform_curve_x.append(1) uniform_curve_y.append(maxvalue) uniform_curve_x.insert(0,0) uniform_curve_y.insert(0,maxvalue) return uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf)",
"plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show() heatmap,",
"found. E2\".format(position1)) if found == True: newx2.append(xvals[loc]) newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69:",
"= np.histogram2d(hist_values1, hist_values3, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2),",
"mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if",
"= True prev_highest.append(position2) prev_highest_position.append(xvals[loc]) #plt.axvline(xvals[loc],c='m') if j>=len(n_hist) and found==False: raise Exception(\"Corresponding position for",
"as f: hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with",
"color='g', label='Mean') plt.vlines(x=(mean-standard_dev), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev),",
"ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c',",
"newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_total_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \",",
"ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003)",
"found==False: raise Exception(\"Corresponding position for probability=({}) not found. E2\".format(position1)) if found == True:",
"hist_values2 = f.read().splitlines() with open('hist_values3.txt') as f: hist_values3 = f.read().splitlines() with open('hist_values4.txt') as",
"\"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL SELECTOR: ######################################## bin_heights, bin_borders, _ = n_hist, b_hist,",
"as mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with open('hist_values1.txt') as",
"plt.xlabel('Total Duration Phase') plt.ylabel('Marginalised Chi-Squared PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2),",
"mticker from mpl_toolkits.axes_grid1.inset_locator import inset_axes # Import MCMC results with open('hist_values1.txt') as f:",
"break else: i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric2.pdf') plt.show() ### y,x,_=plt.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\")",
"= np.histogram2d(hist_values1, hist_values5, bins=(100,100),normed=True) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig, ((ax1, ax2),",
"i+=1 print testcondition if savefigures == True: plt.savefig('asymmetric3.pdf') plt.show() ### xpoints1=np.linspace(0,len(hist_values1),num=len(hist_values1)) xpoints2=np.linspace(0,len(hist_values2),num=len(hist_values2)) plt.scatter(xpoints1,hist_values1,c='r',s=3)",
"# for simplicity. print \"Start...\" # Import modules import numpy as np import",
"cax=axins1, orientation=\"vertical\") ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total",
"ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$')",
"ax2.axis('off') ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase')",
"ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised PDF') ax3.set_xlim(np.min(hist_values2),np.max(hist_values2)) ax3.set_ylim(np.min(hist_values5),np.max(hist_values5)) if savefigures==True: plt.savefig('corner-modified3.pdf') plt.show() ########################################",
"color='m', label='$2\\sigma_-$') plt.vlines(x=(mean2+standard_dev2), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean2+standard_dev2*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend()",
"color='b', label='$\\sigma_+$') plt.vlines(x=(mean3+standard_dev3*2), ymin=0, ymax=y.max()*(1.05), color='c', label='$2\\sigma_+$') plt.legend() if savefigures==True: plt.savefig('PDF3-modified.pdf') plt.show() n_hist,",
"are relevant, but the code has been kept in this single file #",
"uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices): total_amount = total_amount +",
"PDF') if savefigures == True: plt.savefig('plottemp2.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\",",
"hist_values3=[float(i) for i in hist_values3] hist_values4=[float(i) for i in hist_values4] hist_values5=[float(i) for i",
"i in range(Nslices): total_amount = total_amount + modeldata2['bin_values'][Nslices-i-1] fractional_flux = (total_amount+flux_star)/(flux_star) uniform_curve_x.append(plotrange2[i]) uniform_curve_y.append(fractional_flux)",
"plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True: plt.savefig('final-mcmc-lightcurve1.pdf') plt.show()",
"True: plt.savefig('plottemp.pdf') bin_max = np.where(n_hist == n_hist.max()) print \"Mode:\", b_hist[bin_max][0] ### CONFIDENCE INTERVAL",
"plt.savefig('PDF2-modified.pdf') plt.show() n_hist, b_hist, patches_hist = plt.hist(hist_values2,bins=200,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\",label=\"PDF\") plt.hist(hist_values2,bins=200,normed=1,facecolor=\"black\",edgecolor='None',alpha=0.1,label=\"PDF\") plt.xlabel('Total Occultation Duration') plt.ylabel('Normalised PDF')",
"PDF') plt.ylim(0,y.max()*(1.05)) plt.vlines(x=(mean2), ymin=0, ymax=y.max()*(1.05), color='g', label='Mean') plt.vlines(x=(mean2-standard_dev2), ymin=0, ymax=y.max()*(1.05), color='r', label='$\\sigma_-$') plt.vlines(x=(mean2-standard_dev2*2),",
"P_total, Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount =",
"#No-limb model #modeldata2=np.genfromtxt('nolimbgress1.txt', names=True, delimiter=';',dtype=None) # Import graph specifications graphspecs=np.genfromtxt('graph_specs.txt', names=True, delimiter=';',dtype=None) P_total,P_full,P,flux_star,t_occultation,Initial,Length,Nslices=graphspecs['P_total'],graphspecs['P_full'],graphspecs['P'],graphspecs['flux_star'],graphspecs['t_occultation'],graphspecs['Initial'],graphspecs['Length'],graphspecs['Nslices']",
"dx=5) print \"area =\", area summation1=0 summation2=0 prev_highest=[0] prev_highest_position=[1e9] i=0 newx1=[] newy1=[] newx2=[]",
"newy2.append(position2) break summation2=np.abs(np.trapz(newy2,x=newx2)) testcondition=1-(summation1+summation2) if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \",",
"plt.subplots(2, 2, sharex='col', sharey='row') contourplot=ax3.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys') ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight')",
"Phase') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist5.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values2, hist_values3, bins=(100,100),normed=True)",
"np.abs(maxvalx-newx1[-1]) print \"Upper: \", np.abs(maxvalx-newx2[-1]) break else: i+=1 #plt.axvline(xvals[i],c='b') print testcondition if savefigures",
"Length plotrange=np.linspace(-P_total+Initial,-P_full+Initial, num=Nslices) plotrange2=np.linspace(P_full+Initial,P_total+Initial, num=Nslices) stepdifference=np.abs(plotrange[0]-plotrange[1]) rangedifference=np.abs(plotrange2[0]-plotrange[-1]) Nsteps_needed=int(round(rangedifference/stepdifference)) plotrange3=np.linspace(plotrange[-1]+stepdifference,plotrange2[0]-stepdifference,num=Nsteps_needed) uniform_curve_x,uniform_curve_y=[],[] total_amount = np.sum(modeldata1['bin_values'])",
"PDF') ax3.set_xlim(np.min(hist_values1),np.max(hist_values1)) ax3.set_ylim(np.min(hist_values2),np.max(hist_values2)) if savefigures==True: plt.savefig('corner-modified.pdf') plt.show() heatmap, xedges, yedges = np.histogram2d(hist_values1, hist_values5,",
"function def generate_model(full,tot,mid,verbose): Initial=mid P_full=full P_total=tot if verbose==True: print \"Details: \", Initial, P_full,",
"open('hist_values4.txt') as f: hist_values4 = f.read().splitlines() with open('hist_values5.txt') as f: hist_values5 = f.read().splitlines()",
"Import modules import numpy as np import matplotlib.pyplot as plt from lmfit.models import",
"plt.show() plt.hist2d(hist_values1,hist_values3, bins=100) plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100)",
"#plt.colorbar(contourplot,ax=ax3) ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values5,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position')",
"ax3.axis('tight') ax3.ticklabel_format(useOffset=False) myLocator = mticker.MultipleLocator(0.0003) ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Position') ax3.set_ylabel('Full Duration') ax1.set_ylabel('Marginalised PDF') ax4.set_xlabel('Marginalised",
"if testcondition<0.69: plt.axvline(maxvalx,c='k') plt.axvline(P_full_initial,c='r') plt.axvline(newx1[-1],c='#505050') plt.axvline(newx2[-1],c='#505050') print \"Lower: \", np.abs(maxvalx-newx1[-1]) print \"Upper: \",",
"ax1.hist(hist_values2,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Total Duration Phase') ax3.set_ylabel('Chi-Squared",
"maxval=result.best_fit[i] maxvalx=xvals[i] print \"Curve Mode:\", maxvalx area = np.trapz(result.best_fit, x=xvals)#, dx=5) print \"area",
"MCMC (to simplify maths) hist_values2=np.array(hist_values2)*2 hist_values5=np.array(hist_values5)*2 include_middle=True if include_middle==True: inputfile='generated_data1' if include_middle==False: inputfile='generated_data_nomid'",
"= inset_axes(ax3, width=\"5%\", height=\"92.5%\", loc=1) plt.colorbar(contourplot, cax=axins1, orientation=\"vertical\")#, ticks=[1, 2, 3]) #plt.colorbar(contourplot,ax=ax3) ax2.axis('off')",
"label='$\\sigma_-$') plt.vlines(x=(mean-standard_dev*2), ymin=0, ymax=y.max()*(1.05), color='m', label='$2\\sigma_-$') plt.vlines(x=(mean+standard_dev), ymin=0, ymax=y.max()*(1.05), color='b', label='$\\sigma_+$') plt.vlines(x=(mean+standard_dev*2), ymin=0,",
"i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in range(Nslices): total_amount",
"ax2.axis('off') ax1.hist(hist_values1,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\") ax4.hist(hist_values3,bins=100,normed=1,edgecolor=\"black\",facecolor=\"black\",histtype=\"step\", orientation=\"horizontal\") ax3.axis('tight') ax3.ticklabel_format(useOffset=False) #myLocator = mticker.MultipleLocator(0.00) #ax3.xaxis.set_major_locator(myLocator) ax3.set_xlabel('Midpoint Phase Position')",
"include_middle==True: for i in range(len(plotrange3)): uniform_curve_x.append(plotrange3[i]) uniform_curve_y.append(1.) total_amount = 0 for i in",
"uniform_curve_x,uniform_curve_y interpolation_datax,interpolation_dataf=generate_model(0.00730,0.0080,0.50035,verbose=False) plt.plot(interpolation_datax,interpolation_dataf) plt.scatter(chi2file['x_values'],chi2file['flux_values'],c='b',s=8,lw=0)#,zorder=2) if sigma_value!=0: plt.errorbar(chi2file['x_values'],chi2file['flux_values'],yerr=sigma_value,c='#696969',lw=1,ls='none') plt.xlim(0.47,0.53) plt.ylim(np.min(chi2file['flux_values']),np.max(chi2file['flux_values'])) plt.xlabel('Phase') plt.ylabel('$F(t)/F$') if savefigures==True:",
"print \"Start...\" # Import modules import numpy as np import matplotlib.pyplot as plt",
"plt.xlabel('Midpoint Phase Position') plt.ylabel('Chi-Squared') if savefigures==True: plt.savefig('chisquared-hist1.pdf') plt.show() plt.hist2d(hist_values2,hist_values3, bins=100) plt.xlabel('Total Duration Phase')"
] |
[
"None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records",
"uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия',",
"class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False)",
"подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False,",
"None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records =",
"'Вечная подписка даёт вам все бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum):",
"rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None,",
"= rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy',",
"'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits',",
"'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards',",
"might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records =",
"7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON:",
"= (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2,",
"'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3,",
"судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE: 25, cards_relations.RARITY.EPIC: 50,",
"rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1,",
"'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities',",
"'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7,",
"smart_imports smart_imports.all() INFINIT_PREMIUM_DESCRIPTION = 'Вечная подписка даёт вам все бонусы подписчика на всё",
"'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS',",
"2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений',",
"('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE:",
"full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная",
"('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс",
"предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'),",
"import smart_imports smart_imports.all() INFINIT_PREMIUM_DESCRIPTION = 'Вечная подписка даёт вам все бонусы подписчика на",
"= rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION',",
"на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False)",
"class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка',",
"= rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY',",
"GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription',",
"'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE: 25, cards_relations.RARITY.EPIC: 50, cards_relations.RARITY.LEGENDARY: 100}",
"'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES",
"8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE: 25,",
"= rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION,",
"'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES',",
"('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты",
"'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM',",
"1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference',",
"'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset',",
"'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2,",
"rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class",
"'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8,",
"подписка даёт вам все бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description",
"('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6,",
"= rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column()",
"rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'),",
"4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности',",
"'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-'))",
"'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS',",
"время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required =",
"(('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук',",
"= rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),)",
"(('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid =",
"PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name",
"'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE: 25, cards_relations.RARITY.EPIC: 50, cards_relations.RARITY.LEGENDARY:",
"вам все бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False)",
"'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'),",
"single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None,",
"'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4,",
"бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required =",
"12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column()",
"'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'),",
"всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required",
"'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'),",
"'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10, cards_relations.RARITY.RARE: 25, cards_relations.RARITY.EPIC:",
"smart_imports.all() INFINIT_PREMIUM_DESCRIPTION = 'Вечная подписка даёт вам все бонусы подписчика на всё время",
"('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии',",
"3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты',",
"('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES =",
"= (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid",
"single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная",
"'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix",
"подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0,",
"'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS',",
"даёт вам все бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description =",
"rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records",
"('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5,",
"'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET',",
"= 'Вечная подписка даёт вам все бонусы подписчика на всё время игры.' class",
"rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12,",
"все бонусы подписчика на всё время игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required",
"INFINIT_PREMIUM_DESCRIPTION = 'Вечная подписка даёт вам все бонусы подписчика на всё время игры.'",
"игры.' class PERMANENT_PURCHASE_TYPE(rels_django.DjangoEnum): description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False,",
"'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения', 'preference', 'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'),",
"'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON:",
"('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest', 'random-premium-chest'), ('PREFERENCES', 3, 'предпочтения',",
"records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum):",
"description = rels.Column(unique=False) might_required = rels.Column(unique=False, single_type=False) level_required = rels.Column(unique=False, single_type=False) full_name =",
"'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'),",
"6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans', 'clan-'), ('CARDS', 8, 'Карты судьбы',",
"5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES', 6, 'способности', 'abilities', 'hero-abilities-'), ('CLANS', 7, 'гильдии', 'clans',",
"uid = rels.Column() uid_prefix = rels.Column(unique=False) records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'),",
"level_required = rels.Column(unique=False, single_type=False) full_name = rels.Column() records = (('INFINIT_SUBSCRIPTION', 12, 'Вечная подписка',",
"records = (('PREMIUM', 0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST',",
"INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix = rels.Column(unique=False)",
"подписка', INFINIT_PREMIUM_DESCRIPTION, None, None, 'Вечная подписка'),) class GOODS_GROUP(rels_django.DjangoEnum): uid = rels.Column() uid_prefix =",
"'clan-'), ('CARDS', 8, 'Карты судьбы', 'cards', 'cards-')) CARDS_MIN_PRICES = {cards_relations.RARITY.COMMON: 2, cards_relations.RARITY.UNCOMMON: 10,",
"0, 'подписка', 'subscription', 'subscription-'), ('ENERGY', 1, 'энергия', 'energy', 'energy-'), ('CHEST', 2, 'сундук', 'random-premium-chest',",
"'preference-'), ('PREFERENCES_RESET', 4, 'сброс предпочтений', 'preference-reset', 'hero-preference-reset-'), ('HABITS', 5, 'черты', 'habits', 'hero-habits-'), ('ABILITIES',"
] |
[
"['.tex']) return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase):",
"be a string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if file_name.lower().endswith(ext): return",
"tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if",
"for s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must",
"= str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in",
"[s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name",
".settings import get_setting strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return",
"strbase): raise TypeError('file_name must be a string') tex_file_exts = get_tex_extensions() for ext in",
"isinstance(file_name, strbase): raise TypeError('file_name must be a string') tex_file_exts = get_tex_extensions() for ext",
"get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name):",
"get_setting strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for",
"get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name,",
"str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)]",
"= get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if not",
"tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if file_name.lower().endswith(ext): return True return False",
"a string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if file_name.lower().endswith(ext): return True",
"set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must be a string')",
"must be a string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if file_name.lower().endswith(ext):",
"TypeError('file_name must be a string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if",
"in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must be a",
"raise TypeError('file_name must be a string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts:",
"string') tex_file_exts = get_tex_extensions() for ext in tex_file_exts: if file_name.lower().endswith(ext): return True return",
"def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must be a string') tex_file_exts",
"is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must be a string') tex_file_exts =",
"strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s",
"not isinstance(file_name, strbase): raise TypeError('file_name must be a string') tex_file_exts = get_tex_extensions() for",
"def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower() for s in set(tex_file_exts)] def",
"<filename>latextools_utils/is_tex_file.py from .settings import get_setting strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts',",
"import get_setting strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex']) return [s.lower()",
"s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise TypeError('file_name must be",
"if not isinstance(file_name, strbase): raise TypeError('file_name must be a string') tex_file_exts = get_tex_extensions()",
"from .settings import get_setting strbase = str def get_tex_extensions(): tex_file_exts = get_setting('tex_file_exts', ['.tex'])",
"return [s.lower() for s in set(tex_file_exts)] def is_tex_file(file_name): if not isinstance(file_name, strbase): raise"
] |
[
"########################### # 1 select and sort paths # ########################### files_dirs = [] if",
"fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading =",
"logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform != 'linux'",
"under the MIT License. import argparse import configparser import fnmatch import logging import",
"'~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r}",
"Custom help-argument to have consistent style. add_help=False to enable this. \"\"\" parser.add_argument( '-h',",
"= fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed with renaming?') #",
"Tuples containing the number of directories, files and the names of them after",
"for dirpath, dirnames, filenames in os.walk(base_path): for filename in filenames: full_filepath = dirpath",
"= get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path =",
"args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs =",
"fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆',",
"termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:] args =",
"full_filepath = dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for",
"List from typing import Tuple from spasco import __src_url__ from spasco import __title__",
"nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?',",
"success_msg = fmt(f'All done! {filecount} files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue)",
"within the current working directory are mapped into a list. :returns List of",
"formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir',",
"in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file",
"'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file,",
"the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace",
"if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir:",
"renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the",
"---- if not files_dirs: print('No directory or file present!') return 1 # ------",
"= os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a valid",
"'-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?',",
"'/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath",
"of file- and directory names. \"\"\" # Copyright (c) 2021, <NAME>. # All",
"= [] dircount, filecount = 0, 0 for old_path_name in path_lst: path_base, file",
"files_dirs: print('No file present for renaming.') return 1 filtered_paths = files_dirs ################ #",
"exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__",
"formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging and",
"in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present",
"by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter(",
"args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state:",
"files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the",
"{config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str])",
"command-line arguments, such as sys.argv (including the program name in argv[0]). :return Zero",
"if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp: config.write(fp)",
"and directories are renamed and their names returned. Furthermore, the number fo directories/files",
"files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present",
"settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", )",
"files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths]",
"sub_parsers.add_parser( name='config', description='search-value and new-value can be changed. Logging to record all '",
"files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional",
"a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None:",
"for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?',",
"search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\"",
"name in argv[0]). :return Zero on successful program termination, non-zero otherwise. \"\"\" main_parser,",
"renamed are also returned. :returns Tuples containing the number of directories, files and",
"dest='log_name', help='Set a new filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname',",
"log_state: print('Logging is activated.') else: print('Logging is deactivated.') return 0 if args.log_name: old_logger_path",
"the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value',",
") main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the pattern",
"fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for",
"try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ': ' + str(e) +",
"execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version number and exit.', version=f'%(prog)s",
"new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else: msg = f'You can rename",
"if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present for",
"'\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'],",
"on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename",
"in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None",
"existent ---- if not files_dirs: print('No directory or file present!') return 1 #",
"Boolean logic of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg)",
"log record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\",",
"fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value']",
"+ '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames:",
"file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if",
"nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def",
"renamed and their names returned. Furthermore, the number fo directories/files which were renamed",
"\"' '\": SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() #",
"'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging is deactivated.') return 0 if",
"is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp: config.write(fp)",
"0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool",
"files_dirs.copy() # ------ no file/dir existent ---- if not files_dirs: print('No directory or",
"for x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy():",
"new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path",
"[] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir)",
"main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip",
"# Copyright (c) 2021, <NAME>. # All rights reserved. Distributed under the MIT",
"filtered_paths]) + 4)}\") print() q = fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK",
"get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if",
"all ' 'renaming actions as log file can be activated.', usage=f'{__title__} config [--show-setting]",
"NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths",
"not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a valid directory!') return 1",
"in argv[0]). :return Zero on successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser",
"a list. :returns List of all file/directory paths, recursively and sorted \"\"\" all_files_dirs",
"select and sort paths # ########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir",
"help=f\"Sub-command to interact with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true',",
"ArgumentParser instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is",
"help='Only files/dirs not containing the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true',",
"= argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace function. By default it",
"subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers)",
"args.files_only and not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and not os.path.isfile(x):",
"main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\"",
"nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.', ) main_parser.add_argument( '-e',",
"below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore",
"0 for old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value)",
"else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE = '",
"this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help message and exit.\", )",
"and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured as subparser -----",
"paths, recursively and sorted \"\"\" all_files_dirs = [] base_path = os.getcwd() # collect",
") config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default:",
"vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0 ########################### # 1 select and",
"e: sys.stderr.write(__title__ + ': ' + str(e) + '\\n') sys.exit(1) if __name__ ==",
"files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command",
"str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path =",
"renaming starts with the deepest nested file/directory: files_dirs = [x.split('/') for x in",
"action='help', help=\"Show this help message and exit.\", ) def run_main() -> None: try:",
"(c) 2021, <NAME>. # All rights reserved. Distributed under the MIT License. import",
"dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the current working",
"<NAME>. # All rights reserved. Distributed under the MIT License. import argparse import",
"on successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv =",
"with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new",
"filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform != 'linux' and",
"config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0 ########################### #",
") main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive',",
"new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return",
"not containing the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories",
"as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else:",
") config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\"",
"'-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p',",
"if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!')",
"1 filtered_paths = files_dirs ################ # 3 renaming # ################ if args.new_value ==",
"path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else: msg =",
"file- and directory names. \"\"\" # Copyright (c) 2021, <NAME>. # All rights",
"add_parser_help(main_parser) # ---- configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and",
"= os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1",
"= [] base_path = os.getcwd() # collect all rel. paths in a list",
"textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS',",
"'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w')",
"x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs:",
"os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the metavar below the",
"nargs='?', default=os.listdir(), help='Select a single file or directory for renaming.', ) main_parser.add_argument( '-s',",
"for x in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs:",
"if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if",
"directory names. \"\"\" # Copyright (c) 2021, <NAME>. # All rights reserved. Distributed",
"def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the current working directory are",
"config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path,",
"new filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a",
"settings file and then a logger: config = configparser.ConfigParser() config.read(settings_file) # default values",
"'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg =",
"'-v', '--version', action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) #",
"files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2: path filtration #",
"for platforms other than OS X / linux\") def main(argv: List[str]) -> int:",
"into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming preview and",
"' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The",
"= f\"None of the {len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg)",
"renaming=True, ) success_msg = fmt(f'All done! {filecount} files and {dircount} directories were renamed!",
"if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as",
"'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value:",
"not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories contain the search",
"return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')}",
"files_dirs = [x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs",
"print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path =",
"valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp: config.write(fp)",
"'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new",
"= fmt(f'All done! {filecount} files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg)",
"dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file or directory for renaming.',",
"fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading}",
"your current settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log",
"f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', )",
"for filename in filenames: full_filepath = dirpath + '/' + filename rel_filepath =",
"of all file/directory paths, recursively and sorted \"\"\" all_files_dirs = [] base_path =",
"action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?',",
"# , Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount,",
"are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i',",
"= config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s |",
"search_value: str, new_value: str, renaming: bool = False) -> Tuple[int, int, List[str]]: \"\"\"",
"in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if",
"argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have consistent style. add_help=False to enable",
"get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform !=",
"'': NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value if args.new_value is None:",
"print() q = fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed with",
"= config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging is deactivated.') return",
"\"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace function. By",
") config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument(",
"help='Show version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured",
"x in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x in files_dirs.copy(): if",
"filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path() log_location =",
"= input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming(",
"as f: config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename =",
"{__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings",
"within your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more",
"to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help message and",
"return 1 def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool = False)",
"as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser =",
"{config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str, new_value:",
"= args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS',",
"and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction)",
"__title__ from spasco import __version__ from spasco.term_color import fmt from spasco.term_color import Txt",
"filenames in os.walk(base_path): for filename in filenames: full_filepath = dirpath + '/' +",
"all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath + '/' + dirname rel_dirpath",
"= ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2: path filtration # ########################",
"# collect all rel. paths in a list (rel to cwd): for dirpath,",
"------ dirs-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and",
"fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x)",
"': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new",
"argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging and rename settings.\",",
"files/dirs not containing the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only",
"max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(),",
"have consistent style. add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show",
"x in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x",
"6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") for before,",
"subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if isinstance(action,",
"return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as",
"structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser",
"is activated.') else: print('Logging is deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path()",
"args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value'",
"'\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",)",
") if (sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not",
"= [] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent ---- if not",
"glorified replace function. By default it replaces whitespaces\\n' f'of all file- and directory",
"fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in",
"for replacing/removing whitespaces or other patterns of file- and directory names. \"\"\" #",
"dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser)",
"filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All",
"config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path,",
"in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE",
"it replaces whitespaces\\n' f'of all file- and directory names within your current working",
"\"\"\" Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value",
"------ # [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)]",
"for old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new",
"old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new =",
"config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename for the logger.', )",
"tool for replacing/removing whitespaces or other patterns of file- and directory names. \"\"\"",
"[] dircount, filecount = 0, 0 for old_path_name in path_lst: path_base, file =",
"Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value",
"args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS',",
"with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return",
"main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\", )",
"program name in argv[0]). :return Zero on successful program termination, non-zero otherwise. \"\"\"",
"if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if '~' in args.log_location: log_location",
"whitespaces or other patterns of file- and directory names. \"\"\" # Copyright (c)",
"were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1",
"'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] =",
"Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames",
"record all ' 'renaming actions as log file can be activated.', usage=f'{__title__} config",
"filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]]",
", Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue,",
"typing import Tuple from spasco import __src_url__ from spasco import __title__ from spasco",
"{__version__}', ) add_parser_help(main_parser) # ---- configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers(",
"{config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS',",
"\"\"\" Custom help-argument to have consistent style. add_help=False to enable this. \"\"\" parser.add_argument(",
"- len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) +",
"filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent ---- if",
"'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' ' filtered_paths =",
"help='Only files/dirs containing the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?',",
"config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging is",
"* (max([len(x) for x in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line *",
"spasco import __src_url__ from spasco import __title__ from spasco import __version__ from spasco.term_color",
"x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy(): if",
"files_dirs ################ # 3 renaming # ################ if args.new_value == '': NEW_VALUE =",
"custom search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define",
"full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount +=",
") main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only',",
"[args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() #",
"is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE ==",
"config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def",
"= fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths]) - len(before))}",
"\"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can be changed. Logging to",
"return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have consistent",
"spasco.term_color import fmt from spasco.term_color import Txt base, file = os.path.split(__file__) settings_file =",
"List of all file/directory paths, recursively and sorted \"\"\" all_files_dirs = [] base_path",
"+ dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing",
"for x in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x in files_dirs.copy():",
"true/false] [-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog,",
"} config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file,",
"[] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent ---- if not files_dirs:",
"nargs='?', action='store', help='Only files/dirs not containing the pattern are renamed.', ) main_parser.add_argument( '-d',",
"created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_', }",
"'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized for platforms other",
"'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if '~'",
"for log record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"'",
"x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg",
"add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help message",
"help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming preview",
"\"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\")",
"and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version number and exit.',",
"for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default:",
"= args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"'",
"format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform != 'linux' and sys.platform !=",
"= os.getcwd() # collect all rel. paths in a list (rel to cwd):",
"metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser:",
"import sys from argparse import _SubParsersAction from argparse import HelpFormatter from typing import",
"= False) -> Tuple[int, int, List[str]]: \"\"\" List of filtered files and directories",
"== \"' '\": SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy()",
"f: config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS',",
"renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else:",
"old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path",
"renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the current working directory",
"if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount +=",
"= os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up a settings file and",
"action): # type: ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter,",
"{' ' * (max([len(x) for x in filtered_paths]) - len('before') + 6)} {after_heading}\",)",
"that renaming starts with the deepest nested file/directory: files_dirs = [x.split('/') for x",
"args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The",
"Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x",
"'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f) def get_logger_path() -> str:",
"if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True,",
"argv: List[str]) -> int: \"\"\" Boolean logic of config subparser triggering. \"\"\" args",
"help='Skip security question, renaming preview and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version',",
"dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done!",
"List[str]) -> int: \"\"\" Boolean logic of config subparser triggering. \"\"\" args =",
"= config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new",
"current working directory are mapped into a list. :returns List of all file/directory",
"as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is",
"os.path.join(base, 'settings.ini') # set up a settings file and then a logger: config",
"= f'You can rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg = fmt(msg)",
"= { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as",
"new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing",
"(max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x)",
"for x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs:",
"file can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]]",
"filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', )",
"None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ': ' + str(e)",
"and directory names. \"\"\" # Copyright (c) 2021, <NAME>. # All rights reserved.",
"not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present for renaming.') return 1",
") config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set",
"# type: ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter):",
"config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser",
"{config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] =",
"of directories, files and the names of them after renaming \"\"\" renamed_paths =",
"!= 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized for platforms",
"'' if args.new_value: NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS',",
"q = fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed with renaming?')",
"the number fo directories/files which were renamed are also returned. :returns Tuples containing",
"return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w')",
"-> int: \"\"\" Main program. :argument argv: command-line arguments, such as sys.argv (including",
"cwd): for dirpath, dirnames, filenames in os.walk(base_path): for filename in filenames: full_filepath =",
"1 # ------ files-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if",
"action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are",
"else: print('Logging is deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] =",
"nargs='?', metavar='filename', dest='log_name', help='Set a new filename for the logger.', ) config_subparser_logging.add_argument( '-l',",
"not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only):",
"_SubParsersAction from argparse import HelpFormatter from typing import List from typing import Tuple",
"to underscores ============================== Command line tool for replacing/removing whitespaces or other patterns of",
"1 # ------ except-pattern filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if",
"get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if",
"before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue)",
"files and directories are renamed and their names returned. Furthermore, the number fo",
"argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None) == 'config':",
"from spasco import __title__ from spasco import __version__ from spasco.term_color import fmt from",
"(max([len(x) for x in filtered_paths]) + 4)}\") print() q = fmt(' [y/n] ',",
"default it replaces whitespaces\\n' f'of all file- and directory names within your current",
"configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can be changed.",
"filtered_paths = files_dirs ################ # 3 renaming # ################ if args.new_value == '':",
"from typing import List from typing import Tuple from spasco import __src_url__ from",
"filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and not os.path.isfile(x)]",
"get_logger_path() log_location = args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not",
"def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser =",
"permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument",
"successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:]",
"-> None: \"\"\" Custom help-argument to have consistent style. add_help=False to enable this.",
"optimized for platforms other than OS X / linux\") def main(argv: List[str]) ->",
"filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding =",
"file/dir existent ---- if not files_dirs: print('No directory or file present!') return 1",
"config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value",
"MIT License. import argparse import configparser import fnmatch import logging import os import",
"metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the pattern are renamed.', )",
"super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and adds RawDescription",
"is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with",
"X / linux\") def main(argv: List[str]) -> int: \"\"\" Main program. :argument argv:",
"if args.immediately: is_proceeding = 'y' else: msg = f'You can rename {len(filtered_paths)} files",
"files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories contain",
"😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\",",
"+ filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath =",
"max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument(",
"than OS X / linux\") def main(argv: List[str]) -> int: \"\"\" Main program.",
"filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return",
"a glorified replace function. By default it replaces whitespaces\\n' f'of all file- and",
"config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file,",
"and/or directories.' # 🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading",
"the number of directories, files and the names of them after renaming \"\"\"",
"pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter ----- # [files_dirs.remove(x) for x",
"of the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------",
"args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp: config.write(fp)",
"as log file can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]]",
"logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv:",
"is_proceeding = input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames =",
"config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have",
"config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path,",
"(max([len(x) for x in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x)",
"logger: config = configparser.ConfigParser() config.read(settings_file) # default values for log record are created:",
"argparse import HelpFormatter from typing import List from typing import Tuple from spasco",
"config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on')",
"os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",)",
"import HelpFormatter from typing import List from typing import Tuple from spasco import",
"os.getcwd() # collect all rel. paths in a list (rel to cwd): for",
"not files_dirs: print('No file present for renaming.') return 1 filtered_paths = files_dirs ################",
"are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_',",
"args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x):",
"class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and adds RawDescription \"\"\"",
"Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)}",
"os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a valid directory!')",
"files_dirs.remove(x) if not files_dirs: print('No directory present for renaming.') return 1 # ------",
"if (sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized",
"Copyright (c) 2021, <NAME>. # All rights reserved. Distributed under the MIT License.",
"| %(message)s', ) if (sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is",
"return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)}",
"else: msg = f'You can rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg",
"file present for renaming.') return 1 filtered_paths = files_dirs ################ # 3 renaming",
"# ------ search-value filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE",
"---- configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration',",
"metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only',",
"Command line tool for replacing/removing whitespaces or other patterns of file- and directory",
"files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and",
"action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern',",
"# ########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir",
"'-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument(",
"names within your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files",
"sort paths # ########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir]",
"fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS',",
"renaming.') return 1 filtered_paths = files_dirs ################ # 3 renaming # ################ if",
"if SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs",
"######################## SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE",
"bool = False) -> Tuple[int, int, List[str]]: \"\"\" List of filtered files and",
"value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter ------ # [files_dirs.remove(x) for",
"| naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]:",
"pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.', )",
"configparser import fnmatch import logging import os import sys from argparse import _SubParsersAction",
"* (max([len(x) for x in filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths,",
"open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log",
"= sub_parsers.add_parser( name='config', description='search-value and new-value can be changed. Logging to record all",
"configparser.ConfigParser() config.read(settings_file) # default values for log record are created: if not config.read(settings_file):",
"+ q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE,",
"sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x in filtered_paths])",
"files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and",
"'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom",
"= config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE =",
"is a glorified replace function. By default it replaces whitespaces\\n' f'of all file-",
"a settings file and then a logger: config = configparser.ConfigParser() config.read(settings_file) # default",
"x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x",
"file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up a settings file",
"{os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() ->",
"if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE",
"as sys.argv (including the program name in argv[0]). :return Zero on successful program",
"open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0",
"{config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic of",
"{ 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f:",
"args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern matching files/directories contain the",
"filtered files and directories are renamed and their names returned. Furthermore, the number",
"consistent style. add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this",
"config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename')",
"not files_dirs: print(f'None of the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return",
"immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}',",
"args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not",
"SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs =",
"fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x in filtered_paths]) - len('before')",
"renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: '",
"main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace function. By default",
"def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic of config subparser",
"not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if",
"SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------ no",
"print('Logging is activated.') else: print('Logging is deactivated.') return 0 if args.log_name: old_logger_path =",
"Logging to record all ' 'renaming actions as log file can be activated.',",
"q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE,",
"them after renaming \"\"\" renamed_paths = [] dircount, filecount = 0, 0 for",
"+ '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack",
"with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else:",
") if SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' ' filtered_paths = []",
"all_files_dirs = [] base_path = os.getcwd() # collect all rel. paths in a",
"nested file/directory: files_dirs = [x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs, key=len,",
"args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize()",
"help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only",
"-> Tuple[int, int, List[str]]: \"\"\" List of filtered files and directories are renamed",
"Distributed under the MIT License. import argparse import configparser import fnmatch import logging",
"'renaming actions as log file can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false]",
"base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up a settings",
"log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value == '",
"files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present",
"= add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for",
"%(message)s', ) if (sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently",
"args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present for renaming.')",
"proceed_msg = fmt('OK to proceed with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg",
"new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount} files and {dircount} directories were",
"Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')}",
"'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log',",
"open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0",
"rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the metavar",
"present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only",
"is_proceeding = 'y' else: msg = f'You can rename {len(filtered_paths)} files and/or directories.'",
"+ 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") for",
"os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not",
"config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file location for the logger.',",
"is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a",
"names of them after renaming \"\"\" renamed_paths = [] dircount, filecount = 0,",
"%(asctime)s | %(message)s', ) if (sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r}",
"epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), )",
"if args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and not",
") main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true',",
"= args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path)",
"= fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading",
"new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as",
"description=f'Spasco is a glorified replace function. By default it replaces whitespaces\\n' f'of all",
"pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command",
"metavar='filename', dest='log_name', help='Set a new filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?',",
"files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return 1",
"return 0 ########################### # 1 select and sort paths # ########################### files_dirs =",
"after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{'",
"= 'y' else: msg = f'You can rename {len(filtered_paths)} files and/or directories.' #",
"args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\")",
"else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS',",
"'--immediately', action='store_true', help='Skip security question, renaming preview and execute immediately.', ) main_parser.add_argument( '-v',",
"args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",)",
"present for renaming.') return 1 filtered_paths = files_dirs ################ # 3 renaming #",
"# default values for log record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] =",
"= [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files()",
"__version__ from spasco.term_color import fmt from spasco.term_color import Txt base, file = os.path.split(__file__)",
"'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp:",
"'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if",
"is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str,",
"metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern',",
"Zero on successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv",
"help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.',",
"0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as",
"not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as",
"and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized for platforms other than",
"List[str]: \"\"\" All files/directories within the current working directory are mapped into a",
"_format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class",
"dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in",
"interact with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your",
"file present!') return 1 # ------ search-value filter ------ # [files_dirs.remove(x) for x",
"} with open(settings_file, 'w') as f: config.write(f) def get_logger_path() -> str: logger_location =",
"if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and",
"more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments:",
"dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.', ) main_parser.add_argument(",
"config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda",
"help=\"Show this help message and exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv))",
"= [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive:",
"dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the pattern are renamed.', ) main_parser.add_argument(",
"new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path()",
"in os.walk(base_path): for filename in filenames: full_filepath = dirpath + '/' + filename",
"file and then a logger: config = configparser.ConfigParser() config.read(settings_file) # default values for",
"'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename",
"spaces to underscores ============================== Command line tool for replacing/removing whitespaces or other patterns",
"'w') as f: config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename",
"log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a",
"metavar='search_value', help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store',",
"' * (max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line",
"choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename',",
"new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return",
"of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0",
"[files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in",
"arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file or",
"with the deepest nested file/directory: files_dirs = [x.split('/') for x in files_dirs] sorted_paths",
"[files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x in",
"or file present!') return 1 # ------ search-value filter ------ # [files_dirs.remove(x) for",
"if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state =",
"f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on:",
"if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest paths first) so that",
"), help=f\"Sub-command to interact with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings',",
"a single file or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store',",
"sort paths (longest paths first) so that renaming starts with the deepest nested",
"{old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All",
"\"' '\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS',",
"config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool =",
"names. \"\"\" # Copyright (c) 2021, <NAME>. # All rights reserved. Distributed under",
"to have consistent style. add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help',",
"renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately',",
"config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n',",
"os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\"",
"metavar='pathname', dest='log_location', help='Set a new file location for the logger.', ) config_subparser_renaming =",
"config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is",
"x in filtered_paths]) + 4)}\") print() q = fmt(' [y/n] ', Txt.pink) proceed_msg",
"Tuple[int, int, List[str]]: \"\"\" List of filtered files and directories are renamed and",
"[y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed with renaming?') # , Txt.greenblue",
"present for renaming.') return 1 # ------ files-only filter ----- # [files_dirs.remove(x) for",
"list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' *",
"the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if",
"open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is",
"== \"''\" or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths =",
"files_dirs.remove(x) if not files_dirs: print('No file present for renaming.') return 1 filtered_paths =",
"fmt(f'All done! {filecount} files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return",
"for x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in",
"return 0 if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if '~' in",
"from typing import Tuple from spasco import __src_url__ from spasco import __title__ from",
"int, List[str]]: \"\"\" List of filtered files and directories are renamed and their",
"metavar of config subparser and adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser,",
"if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS']",
"naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\"",
"f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f) def get_logger_path() ->",
"-> List[str]: \"\"\" All files/directories within the current working directory are mapped into",
"'\": SEARCH_VALUE = ' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------",
"open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0",
"str, renaming: bool = False) -> Tuple[int, int, List[str]]: \"\"\" List of filtered",
"new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location:",
"the command line arguments. :returns An ArgumentParser instance for the CLI. \"\"\" main_parser",
") config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to",
"removing the metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action):",
"contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter ------",
"is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, )",
"be changed. Logging to record all ' 'renaming actions as log file can",
"None) == 'config': execute_config(config_subparser, argv) return 0 ########################### # 1 select and sort",
"= log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path)",
"directory names within your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your",
"'-h', '--help', action='help', help=\"Show this help message and exit.\", ) def run_main() ->",
"args.new_value == '': NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value if args.new_value",
"config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file,",
"import __title__ from spasco import __version__ from spasco.term_color import fmt from spasco.term_color import",
"= recurse_dirs_and_files() # sort paths (longest paths first) so that renaming starts with",
"directories.' # 🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading =",
"style. add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help",
"if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present for",
"print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") print() q = fmt('",
"with open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging",
"and sorted \"\"\" all_files_dirs = [] base_path = os.getcwd() # collect all rel.",
"]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s",
"activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h, --help ]',",
"# ---- configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming",
"config = configparser.ConfigParser() config.read(settings_file) # default values for log record are created: if",
"x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No",
"[-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command",
"base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the metavar below the subparsers",
"!= 'darwin'): print(f\"{__title__!r} is currently not optimized for platforms other than OS X",
"file or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define",
"then a logger: config = configparser.ConfigParser() config.read(settings_file) # default values for log record",
"'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s |",
"--help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with",
"changed. Logging to record all ' 'renaming actions as log file can be",
"and new-value can be changed. Logging to record all ' 'renaming actions as",
"# 1 select and sort paths # ########################### files_dirs = [] if isinstance(args.file_or_dir,",
"'--help', action='help', help=\"Show this help message and exit.\", ) def run_main() -> None:",
"if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount,",
"if args.new_value == '': NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value if",
"the names of them after renaming \"\"\" renamed_paths = [] dircount, filecount =",
"Constructs the main_parser for the command line arguments. :returns An ArgumentParser instance for",
"4)}\") print() q = fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed",
"List[str], search_value: str, new_value: str, renaming: bool = False) -> Tuple[int, int, List[str]]:",
"contain the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter ----- # [files_dirs.remove(x)",
"except Exception as e: sys.stderr.write(__title__ + ': ' + str(e) + '\\n') sys.exit(1)",
"fo directories/files which were renamed are also returned. :returns Tuples containing the number",
"the MIT License. import argparse import configparser import fnmatch import logging import os",
"' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default:",
"'{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter ------ # [files_dirs.remove(x) for x",
"files_dirs: print('No directory present for renaming.') return 1 # ------ files-only filter -----",
"and not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x)",
"if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a valid directory!') return",
"files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and",
"len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\")",
"number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured as subparser",
"search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else: msg = f'You can",
"NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE",
"sys.stderr.write(__title__ + ': ' + str(e) + '\\n') sys.exit(1) if __name__ == '__main__':",
"1 # ------ search-value filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs if",
"{fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def",
"4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming =",
"for renaming.') return 1 filtered_paths = files_dirs ################ # 3 renaming # ################",
"main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument(",
"print(f'The given path {args.log_location!r} is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] =",
"import os import sys from argparse import _SubParsersAction from argparse import HelpFormatter from",
"action='store_true', help='Skip security question, renaming preview and execute immediately.', ) main_parser.add_argument( '-v', '--version',",
"for x in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for",
"Furthermore, the number fo directories/files which were renamed are also returned. :returns Tuples",
"1 def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool = False) ->",
"'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\",",
":returns Tuples containing the number of directories, files and the names of them",
"= get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform",
"and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for logging",
"working directory are mapped into a list. :returns List of all file/directory paths,",
"given path {args.log_location!r} is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location",
"+= 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} | naming:",
"= configparser.ConfigParser() config.read(settings_file) # default values for log record are created: if not",
"is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value']",
"(default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the",
"renaming # ################ if args.new_value == '': NEW_VALUE = '' if args.new_value: NEW_VALUE",
"subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on:",
"sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized for platforms other than OS",
"config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'],",
"program termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:] args",
"len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\")",
"all file- and directory names within your current working directory by \\n' f'underscores.\\n\\nsrc:",
"'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], }",
"path filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value',",
"f'of all file- and directory names within your current working directory by \\n'",
"program. :argument argv: command-line arguments, such as sys.argv (including the program name in",
"dirpath, dirnames, filenames in os.walk(base_path): for filename in filenames: full_filepath = dirpath +",
"nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value',",
"[files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x in",
"add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true',",
"action='store', nargs='?', default=os.listdir(), help='Select a single file or directory for renaming.', ) main_parser.add_argument(",
"location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value == ' ':",
"'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean",
":return Zero on successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser()",
"args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest paths first)",
"log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging is deactivated.')",
"path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new)",
"help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', )",
"config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a",
"= ' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir",
"in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only",
"not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)}",
"= get_logger_path() log_location = args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if",
"to record all ' 'renaming actions as log file can be activated.', usage=f'{__title__}",
"(config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction):",
"and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present for renaming.') return",
"int: \"\"\" Main program. :argument argv: command-line arguments, such as sys.argv (including the",
"__build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command',",
"be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h, --help",
"the deepest nested file/directory: files_dirs = [x.split('/') for x in files_dirs] sorted_paths =",
"{config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if",
"'-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file location for the logger.', )",
"with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current",
"searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\"",
"path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else: msg = f'You",
"bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x in",
"🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink,",
"2: path filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS',",
"= main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv)",
"not in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x)",
") if args.immediately: is_proceeding = 'y' else: msg = f'You can rename {len(filtered_paths)}",
"in filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before,",
"################ if args.new_value == '': NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value",
"directories/files which were renamed are also returned. :returns Tuples containing the number of",
"1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r}",
"dirnames, filenames in os.walk(base_path): for filename in filenames: full_filepath = dirpath + '/'",
"main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file or directory",
"' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent ----",
"fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging",
"to proceed with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg + q) if",
"typing import List from typing import Tuple from spasco import __src_url__ from spasco",
"search-value filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not in",
"a new file location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings',",
"metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type:",
"x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst",
"'y' else: msg = f'You can rename {len(filtered_paths)} files and/or directories.' # 🔨",
"version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured as subparser ----- config_subparsers =",
"class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction): return \"\"",
"a new filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set",
"= { 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\",",
"renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower() == 'y':",
"returned. Furthermore, the number fo directories/files which were renamed are also returned. :returns",
"for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for",
"directory present for renaming.') return 1 # ------ files-only filter ----- # [files_dirs.remove(x)",
") config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file location for the",
"return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp)",
"config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser,",
"= [x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs =",
"and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1],",
"= fmt('OK to proceed with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg +",
"security question, renaming preview and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show",
"= args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE ==",
"(filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the current",
"sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ########################",
"dircount, filecount = 0, 0 for old_path_name in path_lst: path_base, file = os.path.split(old_path_name)",
"argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config',",
"from argparse import HelpFormatter from typing import List from typing import Tuple from",
"= fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x in filtered_paths]) -",
"and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present for renaming.') return",
"fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS',",
"NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if",
"help message and exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception",
"(default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename for",
"help-argument to have consistent style. add_help=False to enable this. \"\"\" parser.add_argument( '-h', '--help',",
"{args.pattern_only!r}!') return 1 # ------ except-pattern filter ----- # [files_dirs.remove(x) for x in",
"= 0, 0 for old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name =",
"An ArgumentParser instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco",
"filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new",
"# ######################## SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if",
"for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified",
"# hack for removing the metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter):",
"'-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\", )",
"underscores ============================== Command line tool for replacing/removing whitespaces or other patterns of file-",
"argv: command-line arguments, such as sys.argv (including the program name in argv[0]). :return",
"to interact with {__title__}'s logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns",
"dircount += 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} |",
"patterns of file- and directory names. \"\"\" # Copyright (c) 2021, <NAME>. #",
"# 🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before',",
"fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if",
"main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the pattern are",
"open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value']",
"not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories",
"= dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname",
"\"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f) def",
"if not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories contain the",
"args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present for renaming.')",
"print('No directory present for renaming.') return 1 # ------ files-only filter ----- #",
"files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only",
"the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file location",
"spasco import __version__ from spasco.term_color import fmt from spasco.term_color import Txt base, file",
"renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount",
"{full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within",
"return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and adds",
"except-pattern filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1],",
"reserved. Distributed under the MIT License. import argparse import configparser import fnmatch import",
"Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command line arguments. :returns An",
"the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs",
"new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value ==",
"run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ': '",
"argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace function. By default it replaces",
"logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic",
"os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location:",
"{__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ),",
"the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only",
"dirnames: full_dirpath = dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath)",
"replace function. By default it replaces whitespaces\\n' f'of all file- and directory names",
"sys.argv (including the program name in argv[0]). :return Zero on successful program termination,",
"x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories",
"= fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x",
"files_dirs: print(f'None of the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1",
"args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given",
"filecount = 0, 0 for old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name",
"'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' ' filtered_paths",
"as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value",
"print('No directory or file present!') return 1 # ------ search-value filter ------ #",
"renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r',",
"list. :returns List of all file/directory paths, recursively and sorted \"\"\" all_files_dirs =",
"dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only',",
"import fmt from spasco.term_color import Txt base, file = os.path.split(__file__) settings_file = os.path.join(base,",
"{dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink))",
"= os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath + '/'",
"config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is",
"List of filtered files and directories are renamed and their names returned. Furthermore,",
"renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) ->",
"'--show-settings', action='store_true', help='Returns your current settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging",
"\"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] =",
") success_msg = fmt(f'All done! {filecount} files and {dircount} directories were renamed! ✨💄✨',",
"and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present",
"= config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig(",
"for x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs:",
"Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") print() q",
"CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a glorified replace function.",
"x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs: if",
"x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not",
"args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as",
"--> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories",
"the program name in argv[0]). :return Zero on successful program termination, non-zero otherwise.",
"if not files_dirs: print(f'None of the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',)",
"function. By default it replaces whitespaces\\n' f'of all file- and directory names within",
"description='search-value and new-value can be changed. Logging to record all ' 'renaming actions",
"in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path {args.log_location!r} is",
"replacing/removing whitespaces or other patterns of file- and directory names. \"\"\" # Copyright",
"for path_as_lst in sorted_paths] ######################## # 2: path filtration # ######################## SEARCH_VALUE =",
"file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new):",
"'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.')",
") config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for logging and renaming.', )",
"{config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS',",
"{SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter ----- # [files_dirs.remove(x) for x in",
"logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path()",
"# , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After',",
"============================== Command line tool for replacing/removing whitespaces or other patterns of file- and",
"\"\"\" Constructs the main_parser for the command line arguments. :returns An ArgumentParser instance",
"print(searchval_msg) return 1 # ------ pattern-only filter ------ # [files_dirs.remove(x) for x in",
"or other patterns of file- and directory names. \"\"\" # Copyright (c) 2021,",
"x in filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming =",
"done! {filecount} files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0",
"record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value':",
"NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE,",
"= \"' '\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is",
"argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic of config subparser triggering. \"\"\"",
"directories are renamed and their names returned. Furthermore, the number fo directories/files which",
"settings_file = os.path.join(base, 'settings.ini') # set up a settings file and then a",
"filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath",
"# [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x",
"not files_dirs: print('No directory or file present!') return 1 # ------ search-value filter",
"action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming",
"'': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value'",
"config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w')",
"Txt.pink) proceed_msg = fmt('OK to proceed with renaming?') # , Txt.greenblue is_proceeding =",
"'darwin'): print(f\"{__title__!r} is currently not optimized for platforms other than OS X /",
"help='Select a single file or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?',",
"up a settings file and then a logger: config = configparser.ConfigParser() config.read(settings_file) #",
"search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp:",
"full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working",
"isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive:",
"into a list. :returns List of all file/directory paths, recursively and sorted \"\"\"",
"files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter ----- #",
"path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount} files and {dircount}",
"for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after,",
"in filenames: full_filepath = dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path)",
"permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", )",
"rights reserved. Distributed under the MIT License. import argparse import configparser import fnmatch",
":returns An ArgumentParser instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False,",
"= f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)}",
"= os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming:",
"this help message and exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv)) except",
"subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0 ########################### # 1",
"\"\"\"spasco - spaces to underscores ============================== Command line tool for replacing/removing whitespaces or",
"files_dirs = recurse_dirs_and_files() # sort paths (longest paths first) so that renaming starts",
"and the names of them after renaming \"\"\" renamed_paths = [] dircount, filecount",
"# 3 renaming # ################ if args.new_value == '': NEW_VALUE = '' if",
"'_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with",
"== '': NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value if args.new_value is",
"None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"':",
"else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value",
"def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool = False) -> Tuple[int,",
"key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2: path",
"to cwd): for dirpath, dirnames, filenames in os.walk(base_path): for filename in filenames: full_filepath",
"paths # ########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if",
"# [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x",
"base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath + '/' + dirname",
"search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename:",
"renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false',",
"as e: sys.stderr.write(__title__ + ': ' + str(e) + '\\n') sys.exit(1) if __name__",
"'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"'",
"settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\",",
"\\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog,",
"config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE = ' '",
"filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)]",
"* (max([len(x) for x in filtered_paths]) + 4)}\") print() q = fmt(' [y/n]",
"pattern-only filter ------ # [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and not",
"adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser",
"1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log",
"if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern",
"{fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") print()",
"Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths])",
"add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser(",
"directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return",
"prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir',",
"'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f)",
"-> None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ': ' +",
"------ except-pattern filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and",
"[files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x in",
"if args.files_only and not os.path.isfile(x)] for x in files_dirs.copy(): if args.files_only and not",
"settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for logging and renaming.',",
"if not files_dirs: print('No directory present for renaming.') return 1 # ------ files-only",
"args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The",
"return 1 # ------ pattern-only filter ------ # [files_dirs.remove(x) for x in files_dirs.copy()",
"0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The",
"########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and",
"or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths,",
"renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount += 1",
"the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern",
"if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The given path",
"recursively and sorted \"\"\" all_files_dirs = [] base_path = os.getcwd() # collect all",
"# optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single",
"main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true',",
"args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern):",
"1 # ------ pattern-only filter ------ # [files_dirs.remove(x) for x in files_dirs.copy() if",
"= path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y' else: msg",
"if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort",
"triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on']",
"+ ': ' + str(e) + '\\n') sys.exit(1) if __name__ == '__main__': run_main()",
"config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have consistent style.",
"directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value",
"= get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0",
"{ 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename':",
"after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths]) -",
"file location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument(",
"logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if",
"= dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs",
"if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new",
"working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def",
"all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not",
"instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__, add_help=False, description=f'Spasco is a",
"of config subparser and adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]:",
"files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not",
"path {args.log_location!r} is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with",
"Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True)",
"log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path() log_location",
"main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true',",
"if not files_dirs: print('No file present for renaming.') return 1 filtered_paths = files_dirs",
"after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' *",
"# ################ if args.new_value == '': NEW_VALUE = '' if args.new_value: NEW_VALUE =",
"config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return",
"set up a settings file and then a logger: config = configparser.ConfigParser() config.read(settings_file)",
"spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can be changed. Logging",
"the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter ----- # [files_dirs.remove(x) for",
"def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ':",
"if not files_dirs: print('No directory or file present!') return 1 # ------ search-value",
"All rights reserved. Distributed under the MIT License. import argparse import configparser import",
") main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming preview and execute immediately.',",
"== 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg",
"args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest paths first) so that renaming",
"in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in",
"type: ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\"",
"all rel. paths in a list (rel to cwd): for dirpath, dirnames, filenames",
"if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar",
"recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the current working directory are mapped",
"replaces whitespaces\\n' f'of all file- and directory names within your current working directory",
"message and exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as",
"renaming: bool = False) -> Tuple[int, int, List[str]]: \"\"\" List of filtered files",
"for x in filtered_paths]) + 4)}\") print() q = fmt(' [y/n] ', Txt.pink)",
"config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s",
"f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80,",
"metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value',",
"main_parser.add_argument( '-v', '--version', action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser)",
"# [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for",
"enable this. \"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help message and exit.\",",
"can rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg = fmt(msg) # ,",
"for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs:",
"usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False,",
"# set up a settings file and then a logger: config = configparser.ConfigParser()",
"for renaming.') return 1 # ------ files-only filter ----- # [files_dirs.remove(x) for x",
"turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new",
"sys from argparse import _SubParsersAction from argparse import HelpFormatter from typing import List",
"search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom",
"return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s',",
"dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths) def recurse_dirs_and_files()",
"# [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for x",
"str): args.file_or_dir = [args.file_or_dir] if args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs",
"renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f',",
"help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) ->",
"'\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, )",
"0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state",
"dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument( '-n',",
"can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h,",
"main_parser for the command line arguments. :returns An ArgumentParser instance for the CLI.",
"3 renaming # ################ if args.new_value == '': NEW_VALUE = '' if args.new_value:",
"prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?',",
"print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst:",
"= args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS',",
"print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return 1 #",
"is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0 if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location",
"logging and rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for",
"config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '':",
"other patterns of file- and directory names. \"\"\" # Copyright (c) 2021, <NAME>.",
"argv[0]). :return Zero on successful program termination, non-zero otherwise. \"\"\" main_parser, config_subparser =",
"is currently not optimized for platforms other than OS X / linux\") def",
"dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs #",
"not files_dirs: print('No directory present for renaming.') return 1 # ------ files-only filter",
"add_help=False, description=f'Spasco is a glorified replace function. By default it replaces whitespaces\\n' f'of",
"[-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact",
"help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value',",
"logging import os import sys from argparse import _SubParsersAction from argparse import HelpFormatter",
"new_value: str, renaming: bool = False) -> Tuple[int, int, List[str]]: \"\"\" List of",
"log_location = args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location):",
"return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring spasco.",
"execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic of config subparser triggering.",
"logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO, format='%(levelname)s",
"x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None",
"\"\"\" All files/directories within the current working directory are mapped into a list.",
"config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is",
"return (filecount, dircount, renamed_paths) def recurse_dirs_and_files() -> List[str]: \"\"\" All files/directories within the",
"[--show-setting] [-o true/false] [-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog:",
"log file can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n [filename]] [-l",
"argparse import _SubParsersAction from argparse import HelpFormatter from typing import List from typing",
"----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for",
"'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str, new_value: str,",
"-> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command line arguments. :returns",
"[-o true/false] [-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter(",
"dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?',",
"[pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to",
"main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming preview and execute immediately.', )",
"= files_dirs.copy() # ------ no file/dir existent ---- if not files_dirs: print('No directory",
"['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2: path filtration # ######################## SEARCH_VALUE",
"= files_dirs ################ # 3 renaming # ################ if args.new_value == '': NEW_VALUE",
"and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern matching files/directories",
"before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──',",
"os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present for renaming.') return 1 filtered_paths",
"os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value:",
"print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value",
"in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in",
"----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for",
"fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with",
"= '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately:",
"import argparse import configparser import fnmatch import logging import os import sys from",
"import logging import os import sys from argparse import _SubParsersAction from argparse import",
"directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.', )",
"\"\"\" Removes metavar of config subparser and adds RawDescription \"\"\" pass def __build_parser()",
"'/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for",
"# 2: path filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value else config.get(",
"for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy():",
"'-f', '--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse",
"action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.',",
"* (max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line *",
"(including the program name in argv[0]). :return Zero on successful program termination, non-zero",
"renaming \"\"\" renamed_paths = [] dircount, filecount = 0, 0 for old_path_name in",
"print('No file present for renaming.') return 1 filtered_paths = files_dirs ################ # 3",
"a logger: config = configparser.ConfigParser() config.read(settings_file) # default values for log record are",
"and sort paths # ########################### files_dirs = [] if isinstance(args.file_or_dir, str): args.file_or_dir =",
"rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath +",
"after renaming \"\"\" renamed_paths = [] dircount, filecount = 0, 0 for old_path_name",
"msg = f'You can rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg =",
"action='store_true', help='Returns your current settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging =",
"'{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") print() q =",
"level=logging.INFO, format='%(levelname)s | %(asctime)s | %(message)s', ) if (sys.platform != 'linux' and sys.platform",
"config.getboolean('LOG-SETTINGS', 'logging_turned_on') if log_state: print('Logging is activated.') else: print('Logging is deactivated.') return 0",
"x in files_dirs.copy(): if args.files_only and not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No",
"in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg =",
"config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for logging and renaming.', ) add_parser_help(config_subparser)",
"2021, <NAME>. # All rights reserved. Distributed under the MIT License. import argparse",
"MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store',",
"print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\",",
"as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return",
"args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and not",
"files and/or directories.' # 🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print()",
"filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)]",
"print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w') as fp:",
"Exception as e: sys.stderr.write(__title__ + ': ' + str(e) + '\\n') sys.exit(1) if",
"config subparser and adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\"",
") config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename for the logger.',",
"'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\" Boolean logic of config",
"or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom",
"files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter",
"sorted \"\"\" all_files_dirs = [] base_path = os.getcwd() # collect all rel. paths",
"'-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security",
"RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for",
"in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' '",
"rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg = fmt(msg) # , Txt.greenblue",
") config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config')",
"== 'config': execute_config(config_subparser, argv) return 0 ########################### # 1 select and sort paths",
"path_as_lst in sorted_paths] ######################## # 2: path filtration # ######################## SEARCH_VALUE = args.search_value",
"' ' filtered_paths = [] all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent",
"config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value', help=\"Set a new 'search-value'",
"of them after renaming \"\"\" renamed_paths = [] dircount, filecount = 0, 0",
"first) so that renaming starts with the deepest nested file/directory: files_dirs = [x.split('/')",
"= '' if args.new_value: NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE =",
"containing the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only",
"filenames: full_filepath = dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath)",
"{after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") for before, after",
"################ # 3 renaming # ################ if args.new_value == '': NEW_VALUE = ''",
"f'You can rename {len(filtered_paths)} files and/or directories.' # 🔨 colored_msg = fmt(msg) #",
"new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value'",
"number of directories, files and the names of them after renaming \"\"\" renamed_paths",
"main(argv: List[str]) -> int: \"\"\" Main program. :argument argv: command-line arguments, such as",
") # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a",
"- spaces to underscores ============================== Command line tool for replacing/removing whitespaces or other",
"and exit.\", ) def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as e:",
"import Txt base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up",
"a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp:",
"NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE",
"command line arguments. :returns An ArgumentParser instance for the CLI. \"\"\" main_parser =",
"the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter ------ #",
"add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging",
"os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory present for renaming.') return 1 #",
"a list (rel to cwd): for dirpath, dirnames, filenames in os.walk(base_path): for filename",
"arguments. :returns An ArgumentParser instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser( prog=__title__,",
"\"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on': \"False\", 'logger_filename': f'{__title__}.log', 'logger_location':",
"0 if args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if '~' in args.log_location:",
"', Txt.pink) proceed_msg = fmt('OK to proceed with renaming?') # , Txt.greenblue is_proceeding",
"action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store',",
"= fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue)",
"config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\",",
"== '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new",
"the metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): #",
"for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument(",
"args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\"",
"default values for log record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = {",
"title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction): return",
"from spasco.term_color import fmt from spasco.term_color import Txt base, file = os.path.split(__file__) settings_file",
"{config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file,",
"\"\"\" Main program. :argument argv: command-line arguments, such as sys.argv (including the program",
"in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only",
"All files/directories within the current working directory are mapped into a list. :returns",
"# ------ files-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only",
"HelpFormatter from typing import List from typing import Tuple from spasco import __src_url__",
"help='Set a new file location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming",
"if SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not in",
"List[str]) -> int: \"\"\" Main program. :argument argv: command-line arguments, such as sys.argv",
"args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\": SEARCH_VALUE =",
"if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or",
"are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument(",
"'-d', '--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only",
"Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can",
"(rel to cwd): for dirpath, dirnames, filenames in os.walk(base_path): for filename in filenames:",
"settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off",
"and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x)",
"all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None",
"optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file",
"MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and adds RawDescription \"\"\" pass",
"are renamed and their names returned. Furthermore, the number fo directories/files which were",
"with open(settings_file, 'w') as f: config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS',",
"config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",)",
"were renamed are also returned. :returns Tuples containing the number of directories, files",
"not os.path.isfile(x): files_dirs.remove(x) if not files_dirs: print('No file present for renaming.') return 1",
") add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on',",
"directories, files and the names of them after renaming \"\"\" renamed_paths = []",
"import fnmatch import logging import os import sys from argparse import _SubParsersAction from",
"paths in a list (rel to cwd): for dirpath, dirnames, filenames in os.walk(base_path):",
"return 1 # ------ except-pattern filter ----- # [files_dirs.remove(x) for x in files_dirs.copy()",
"directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda prog:",
"search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------ pattern-only filter ------ # [files_dirs.remove(x)",
"== ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as fp: config.write(fp)",
"for removing the metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self,",
"as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value",
"filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths])",
"SEARCH_VALUE not in x.split('/')[-1]] for x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]:",
"settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser:",
"new file location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', )",
"'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path = get_logger_path() logging.basicConfig( filename=logger_path, level=logging.INFO,",
"License. import argparse import configparser import fnmatch import logging import os import sys",
"the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are renamed.',",
"new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with",
"= argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None) ==",
"argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None)",
"in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of",
"config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",)",
"return 0 if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\"",
"# ------ pattern-only filter ------ # [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only",
"+ 4)}\") print() q = fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to",
"{len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter",
"def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have consistent style. add_help=False",
"import _SubParsersAction from argparse import HelpFormatter from typing import List from typing import",
"return 1 # ------ dirs-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy()",
"config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if",
"and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\",",
"\"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and",
"'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned",
"logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o',",
"import List from typing import Tuple from spasco import __src_url__ from spasco import",
"✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg =",
"base_path = os.getcwd() # collect all rel. paths in a list (rel to",
"before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x) for",
"'-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser",
"-> int: \"\"\" Boolean logic of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:])",
"= config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with",
"collect all rel. paths in a list (rel to cwd): for dirpath, dirnames,",
"0, 0 for old_path_name in path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value,",
"args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)}",
"sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2:",
"other than OS X / linux\") def main(argv: List[str]) -> int: \"\"\" Main",
"Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser,",
"prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging and rename",
"working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄', formatter_class=lambda",
"such as sys.argv (including the program name in argv[0]). :return Zero on successful",
"triggering config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0 ###########################",
"not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return",
"and their names returned. Furthermore, the number fo directories/files which were renamed are",
"\"\"\" renamed_paths = [] dircount, filecount = 0, 0 for old_path_name in path_lst:",
"title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers:",
"configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser:",
"for x in filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming",
"as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value:",
"Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {'",
"all_selected_files_dirs = files_dirs.copy() # ------ no file/dir existent ---- if not files_dirs: print('No",
"print(f\"{before_heading} {' ' * (max([len(x) for x in filtered_paths]) - len('before') + 6)}",
"x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy():",
"{filecount} files and {dircount} directories were renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else:",
"all file/directory paths, recursively and sorted \"\"\" all_files_dirs = [] base_path = os.getcwd()",
"paths (longest paths first) so that renaming starts with the deepest nested file/directory:",
"ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes",
"otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) #",
"input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount, dircount, new_pathnames = path_renaming( path_lst=filtered_paths,",
"\"\"\" Boolean logic of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings:",
"and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest",
"return 1 # ------ files-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy()",
"with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return",
"renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming = fmt(after, Txt.blue) print(f\"'{before_renaming}'{' ' * (max([len(x)",
"main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return",
"settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS',",
"current settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings',",
"argv) return 0 ########################### # 1 select and sort paths # ########################### files_dirs",
"fnmatch import logging import os import sys from argparse import _SubParsersAction from argparse",
"linux\") def main(argv: List[str]) -> int: \"\"\" Main program. :argument argv: command-line arguments,",
"exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured as subparser ----- config_subparsers",
"{args.log_location!r} is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file,",
"').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\"",
"in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern",
"with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower() ==",
"nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument(",
"= \"''\" with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS',",
"1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount,",
"new_logger_path) print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if",
"dirs-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and not",
"not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest paths",
"args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w') as fp:",
"exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter",
"print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value']",
"'false'], help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name',",
"execute_config(config_subparser, argv) return 0 ########################### # 1 select and sort paths # ###########################",
"fmt(' [y/n] ', Txt.pink) proceed_msg = fmt('OK to proceed with renaming?') # ,",
"files/directories contain the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter ----- #",
"colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True)",
"\"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering",
"'' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding",
"their names returned. Furthermore, the number fo directories/files which were renamed are also",
"# ------ dirs-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only",
"+ 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink) after_renaming",
"config.read(settings_file) # default values for log record are created: if not config.read(settings_file): config['VALUE-SETTINGS']",
"def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command line",
"= args.turn_log_on.capitalize() with open(settings_file, 'w') as fp: config.write(fp) log_state = config.getboolean('LOG-SETTINGS', 'logging_turned_on') if",
"renaming preview and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version number",
":argument argv: command-line arguments, such as sys.argv (including the program name in argv[0]).",
"os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not",
"and adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the",
"def main(argv: List[str]) -> int: \"\"\" Main program. :argument argv: command-line arguments, such",
"question, renaming preview and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version",
"def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return",
"argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command line arguments. :returns An ArgumentParser",
"== '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE,",
"| %(asctime)s | %(message)s', ) if (sys.platform != 'linux' and sys.platform != 'darwin'):",
"log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The",
"Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x) for x in filtered_paths]) - len('before') +",
"'settings.ini') # set up a settings file and then a logger: config =",
"name='config', description='search-value and new-value can be changed. Logging to record all ' 'renaming",
"dircount, renamed_paths = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, ) if args.immediately: is_proceeding = 'y'",
"config_subparser = __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser",
"the current working directory are mapped into a list. :returns List of all",
"from spasco.term_color import Txt base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') #",
"[] base_path = os.getcwd() # collect all rel. paths in a list (rel",
"fmt from spasco.term_color import Txt base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini')",
") main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\",",
"1 select and sort paths # ########################### files_dirs = [] if isinstance(args.file_or_dir, str):",
"non-zero otherwise. \"\"\" main_parser, config_subparser = __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv)",
"'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help()",
"pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not",
"settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', )",
"not optimized for platforms other than OS X / linux\") def main(argv: List[str])",
"os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up a settings file and then",
"SEARCH_VALUE = args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE ==",
"List[str]]: \"\"\" List of filtered files and directories are renamed and their names",
"in path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base,",
":returns List of all file/directory paths, recursively and sorted \"\"\" all_files_dirs = []",
"action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration",
"files_dirs: searchval_msg = f\"None of the {len(all_selected_files_dirs)} present files/directories contain the search value",
"import __version__ from spasco.term_color import fmt from spasco.term_color import Txt base, file =",
"is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w')",
"'-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.', )",
"\"\"\" parser.add_argument( '-h', '--help', action='help', help=\"Show this help message and exit.\", ) def",
"print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line =",
"search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter ----- # [files_dirs.remove(x) for x",
"Removes metavar of config subparser and adds RawDescription \"\"\" pass def __build_parser() ->",
"\"\"\" List of filtered files and directories are renamed and their names returned.",
"present!') return 1 # ------ search-value filter ------ # [files_dirs.remove(x) for x in",
"'-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing the pattern are renamed.',",
"for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file",
"args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not",
"args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file, 'w')",
"directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path",
"isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of",
"containing the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only', action='store_true', help='Only directories are",
"argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and",
"matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter -----",
"' * (max([len(x) for x in filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line",
"SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of the",
"args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE",
"argparse import configparser import fnmatch import logging import os import sys from argparse",
"can be changed. Logging to record all ' 'renaming actions as log file",
"present files/directories contain the pattern {args.pattern_only!r}!') return 1 # ------ except-pattern filter -----",
"path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming: bool = False) -> Tuple[int, int,",
"os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r}",
"is deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with",
"no file/dir existent ---- if not files_dirs: print('No directory or file present!') return",
"location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s',",
"0 if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with",
"main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are renamed.',",
"main_parser, config_subparser = __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering config",
"filtered_paths]) - len('before') + 6)} {after_heading}\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths])",
"of the {len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1",
"logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location', help='Set a new file location for",
"fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern matching files/directories contain",
"the {len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 #",
"contain the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter ----- # [files_dirs.remove(x)",
"[files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x",
"False) -> Tuple[int, int, List[str]]: \"\"\" List of filtered files and directories are",
"args = main_parser.parse_args(args=argv) # triggering config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser,",
"renamed_paths = [] dircount, filecount = 0, 0 for old_path_name in path_lst: path_base,",
"os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f) def get_logger_path() -> str: logger_location",
"fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain",
"-> argparse.ArgumentParser: \"\"\" Parser for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value",
"dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the",
"print('Logging is deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name",
"recurse_dirs_and_files() # sort paths (longest paths first) so that renaming starts with the",
"(max([len(x) for x in filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)):",
"logic of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return",
"proceed with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower()",
"str, new_value: str, renaming: bool = False) -> Tuple[int, int, List[str]]: \"\"\" List",
"full_dirpath = dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return",
"with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return",
"------ search-value filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not",
"_SubParsersAction): return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config",
"if args.set_search_value: if args.set_search_value == ' ': config['VALUE-SETTINGS']['search_value'] = \"' '\" with open(settings_file,",
"(longest paths first) so that renaming starts with the deepest nested file/directory: files_dirs",
"= path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount} files",
"which were renamed are also returned. :returns Tuples containing the number of directories,",
"files and the names of them after renaming \"\"\" renamed_paths = [] dircount,",
"new-value can be changed. Logging to record all ' 'renaming actions as log",
"in dirnames: full_dirpath = dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath, base_path)",
"add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser for configuring",
"'_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern",
"argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser and adds RawDescription \"\"\" pass def",
"= config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?', metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging",
"if args.show_settings: print(settings_msg) return 0 if args.turn_log_on: config['LOG-SETTINGS']['logging_turned_on'] = args.turn_log_on.capitalize() with open(settings_file, 'w')",
"is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w')",
"fp: config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1",
"logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount, dircount, renamed_paths)",
"in filtered_paths]) + 4)}\") print() q = fmt(' [y/n] ', Txt.pink) proceed_msg =",
"\"\"\" all_files_dirs = [] base_path = os.getcwd() # collect all rel. paths in",
"hack for removing the metavar below the subparsers (config) title class NoSubparsersMetavarFormatter(HelpFormatter): def",
"rel. paths in a list (rel to cwd): for dirpath, dirnames, filenames in",
"----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.dirs_only and not os.path.isdir(x)] for",
"[filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33, ),",
"'--dirs-only', action='store_true', help='Only directories are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files",
"'search_value')} new_value: {config.get('VALUE-SETTINGS', 'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')}",
"/ linux\") def main(argv: List[str]) -> int: \"\"\" Main program. :argument argv: command-line",
"new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif os.path.isfile(full_new):",
"new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount",
"sorted_paths] ######################## # 2: path filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value",
"action='store', help='Only files/dirs not containing the pattern are renamed.', ) main_parser.add_argument( '-d', '--dirs-only',",
"configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', )",
"returned. :returns Tuples containing the number of directories, files and the names of",
"------ pattern-only filter ------ # [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and",
"add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\" Custom help-argument to have consistent style. add_help=False to",
"get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\"",
"= fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' ' * (max([len(x)",
"return 1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path =",
"main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def",
"new 'new-value' permanently.\", ) config_subparser.set_defaults(command='config') return config_subparser def add_parser_help(parser: argparse.ArgumentParser) -> None: \"\"\"",
"return 1 filtered_paths = files_dirs ################ # 3 renaming # ################ if args.new_value",
"single file or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value', nargs='?', action='store', metavar='search_value',",
"spasco import __title__ from spasco import __version__ from spasco.term_color import fmt from spasco.term_color",
"-> str: logger_location = config.get('LOG-SETTINGS', 'logger_location') logger_filename = config.get('LOG-SETTINGS', 'logger_filename') return f\"{logger_location}/{logger_filename}\" logger_path",
"if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1],",
"files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern matching files/directories contain the search-value",
"in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in",
") main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs containing the pattern are",
"as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is",
"os.path.relpath(full_filepath, base_path) all_files_dirs.append(rel_filepath) for dirname in dirnames: full_dirpath = dirpath + '/' +",
"config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The new 'new-value' is",
"number fo directories/files which were renamed are also returned. :returns Tuples containing the",
"subparser and adds RawDescription \"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs",
"deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file,",
"containing the number of directories, files and the names of them after renaming",
"[x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst)",
"config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = { 'Logging_turned_on':",
"\"\"\" pass def __build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the",
"fmt('OK to proceed with renaming?') # , Txt.greenblue is_proceeding = input(proceed_msg + q)",
"values for log record are created: if not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value':",
"paths first) so that renaming starts with the deepest nested file/directory: files_dirs =",
"open(settings_file, 'w') as f: config.write(f) def get_logger_path() -> str: logger_location = config.get('LOG-SETTINGS', 'logger_location')",
"search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount} files and {dircount} directories",
"= os.path.relpath(full_dirpath, base_path) all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the metavar below",
"help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a",
"None: \"\"\" Custom help-argument to have consistent style. add_help=False to enable this. \"\"\"",
"= sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## #",
"file- and directory names within your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}',",
") main_parser.add_argument( '-v', '--version', action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}', )",
"= os.path.join(base, 'settings.ini') # set up a settings file and then a logger:",
"in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only)] for x in files_dirs.copy(): if",
"from argparse import _SubParsersAction from argparse import HelpFormatter from typing import List from",
"# All rights reserved. Distributed under the MIT License. import argparse import configparser",
"Main program. :argument argv: command-line arguments, such as sys.argv (including the program name",
"args.pattern_only)] for x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if",
"(default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value",
"whitespaces\\n' f'of all file- and directory names within your current working directory by",
"metavar='true/false', dest='turn_log_on', choices=['true', 'false'], help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f',",
"print(f'None of the exception-pattern matching files/directories contain the search-value {SEARCH_VALUE!r}.',) return 1 #",
"0 ########################### # 1 select and sort paths # ########################### files_dirs = []",
"nargs='?', metavar='pathname', dest='log_location', help='Set a new file location for the logger.', ) config_subparser_renaming",
"reverse=True) files_dirs = ['/'.join(path_as_lst) for path_as_lst in sorted_paths] ######################## # 2: path filtration",
"arguments, such as sys.argv (including the program name in argv[0]). :return Zero on",
"args.immediately: is_proceeding = 'y' else: msg = f'You can rename {len(filtered_paths)} files and/or",
"# triggering config subparser if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0",
"__build_parser() -> Tuple[argparse.ArgumentParser, argparse.ArgumentParser]: \"\"\" Constructs the main_parser for the command line arguments.",
"\"\"\" # Copyright (c) 2021, <NAME>. # All rights reserved. Distributed under the",
"and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group( 'log settings', ) config_subparser_logging.add_argument( '-o', nargs='?',",
"from spasco import __src_url__ from spasco import __title__ from spasco import __version__ from",
"currently not optimized for platforms other than OS X / linux\") def main(argv:",
"# ------ no file/dir existent ---- if not files_dirs: print('No directory or file",
"NEW_VALUE = '' if args.new_value: NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE",
"os.walk(base_path): for filename in filenames: full_filepath = dirpath + '/' + filename rel_filepath",
"if args.new_value: NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value')",
"filename in filenames: full_filepath = dirpath + '/' + filename rel_filepath = os.path.relpath(full_filepath,",
"aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')} new_value:",
"import Tuple from spasco import __src_url__ from spasco import __title__ from spasco import",
"\"''\" or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount, dircount, renamed_paths = path_renaming(",
"print(f\"The new log location is {config.get('LOG-SETTINGS', 'logger_location')!r}.\",) return 0 if args.set_search_value: if args.set_search_value",
"= main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser",
"prog, max_help_position=33, ), help=f\"Sub-command to interact with {__title__}'s logging and rename settings.\", )",
"def _format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction): return \"\" return super()._format_action_invocation(action)",
"starts with the deepest nested file/directory: files_dirs = [x.split('/') for x in files_dirs]",
"files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of",
"mapped into a list. :returns List of all file/directory paths, recursively and sorted",
"the main_parser for the command line arguments. :returns An ArgumentParser instance for the",
"directory or file present!') return 1 # ------ search-value filter ------ # [files_dirs.remove(x)",
"platforms other than OS X / linux\") def main(argv: List[str]) -> int: \"\"\"",
"By default it replaces whitespaces\\n' f'of all file- and directory names within your",
"'--version', action='version', help='Show version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ----",
"if log_state: print('Logging is activated.') else: print('Logging is deactivated.') return 0 if args.log_name:",
"are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store', help='Only files/dirs not containing",
"filtered_paths]) + 4)}\") for before, after in list(zip(filtered_paths, renamed_paths)): before_renaming = fmt(before, Txt.pink)",
"'new_value')} {fmt(\"log settings:\", Txt.greenblue)} logging_turned_on: {config.getboolean('LOG-SETTINGS', 'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\"",
"= get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log filename is {config.get('LOG-SETTINGS', 'logger_filename')!r}.\",) return 0",
"files_dirs: print('No directory or file present!') return 1 # ------ search-value filter ------",
"file/directory paths, recursively and sorted \"\"\" all_files_dirs = [] base_path = os.getcwd() #",
"your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly",
"config_subparser = add_config_subparser(config_subparsers) return main_parser, config_subparser def add_config_subparser(sub_parsers: argparse._SubParsersAction) -> argparse.ArgumentParser: \"\"\" Parser",
"return all_files_dirs # hack for removing the metavar below the subparsers (config) title",
"from spasco import __version__ from spasco.term_color import fmt from spasco.term_color import Txt base,",
"in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if not files_dirs: print('No directory",
"all_files_dirs # hack for removing the metavar below the subparsers (config) title class",
"preview and execute immediately.', ) main_parser.add_argument( '-v', '--version', action='version', help='Show version number and",
"nargs='?', action='store', metavar='search_value', help=\"Define custom search-value (default: ' ').\", ) main_parser.add_argument( '-n', dest='new_value',",
"'logger_filename': f'{__title__}.log', 'logger_location': os.environ['HOME'], } with open(settings_file, 'w') as f: config.write(f) def get_logger_path()",
"import __src_url__ from spasco import __title__ from spasco import __version__ from spasco.term_color import",
"os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if os.path.isdir(full_new): dircount += 1 elif",
", Txt.greenblue is_proceeding = input(proceed_msg + q) if is_proceeding.lower() == 'y': filecount, dircount,",
"rename settings.\", ) config_subparser.add_argument( '--show-settings', action='store_true', help='Returns your current settings for logging and",
"if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp:",
"version number and exit.', version=f'%(prog)s {__version__}', ) add_parser_help(main_parser) # ---- configuration structured as",
"elif os.path.isfile(full_new): filecount += 1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} -->",
"path_lst: path_base, file = os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name)",
"a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new",
"new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] =",
"------ # [files_dirs.remove(x) for x in all_selected_files_dirs if SEARCH_VALUE not in x.split('/')[-1]] for",
"in sorted_paths] ######################## # 2: path filtration # ######################## SEARCH_VALUE = args.search_value if",
"# [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and not os.path.isfile(x)] for x",
"- len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",) print(f\"{sep_line * (max([len(x) for x in filtered_paths]) +",
"'-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename for the logger.', ) config_subparser_logging.add_argument(",
"print(colored_msg) print() before_heading = fmt('Before', Txt.pink, bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line",
"so that renaming starts with the deepest nested file/directory: files_dirs = [x.split('/') for",
"args.file_or_dir and not args.recursive: files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths",
"os.path.isdir(log_location): print(f'The given path {args.log_location!r} is not a valid directory!') return 1 config['LOG-SETTINGS']['logger_location']",
"----- config_subparsers = main_parser.add_subparsers( title='log and renaming configuration', ) config_subparser = add_config_subparser(config_subparsers) return",
"0 if args.set_new_value == '': config['VALUE-SETTINGS']['new_value'] = \"''\" with open(settings_file, 'w') as fp:",
"for x in all_selected_files_dirs: if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs:",
"for the command line arguments. :returns An ArgumentParser instance for the CLI. \"\"\"",
"{len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return 1 # ------",
"are mapped into a list. :returns List of all file/directory paths, recursively and",
"{len(filtered_paths)} files and/or directories.' # 🔨 colored_msg = fmt(msg) # , Txt.greenblue print(colored_msg)",
"print(f\"{sep_line * (max([len(x) for x in filtered_paths]) + 4)}\") for before, after in",
"'--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question,",
"config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can be changed. Logging to record",
"new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new)",
"fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if args.set_new_value ==",
"your files more computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) #",
"line tool for replacing/removing whitespaces or other patterns of file- and directory names.",
"renaming.') return 1 # ------ files-only filter ----- # [files_dirs.remove(x) for x in",
"files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into directories.', ) main_parser.add_argument(",
"in a list (rel to cwd): for dirpath, dirnames, filenames in os.walk(base_path): for",
"' 'renaming actions as log file can be activated.', usage=f'{__title__} config [--show-setting] [-o",
"return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as fp: config.write(fp)",
"+= 1 logging.info(f\" working dir: {os.getcwd()!r} | naming: {old_path_name!r} --> {full_new!r}\",) return (filecount,",
"actions as log file can be activated.', usage=f'{__title__} config [--show-setting] [-o true/false] [-n",
"config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] = {",
"Txt base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set up a",
"activated.') else: print('Logging is deactivated.') return 0 if args.log_name: old_logger_path = get_logger_path() config['LOG-SETTINGS']['logger_filename']",
"new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')!r}.\") return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str],",
"), ) # optional arguments: main_parser.add_argument( \"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select",
"(sys.platform != 'linux' and sys.platform != 'darwin'): print(f\"{__title__!r} is currently not optimized for",
"x in files_dirs.copy() if args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern)] for x in files_dirs.copy(): if",
") def run_main() -> None: try: sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ +",
"return 0 config_subparser.print_help() return 1 def path_renaming(path_lst: List[str], search_value: str, new_value: str, renaming:",
"args.log_location: old_logger_path = get_logger_path() log_location = args.log_location if '~' in args.log_location: log_location =",
"args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the",
"file/directory: files_dirs = [x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True)",
"'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set a new 'new-value' permanently.\",",
"of filtered files and directories are renamed and their names returned. Furthermore, the",
"parser.add_argument( '-h', '--help', action='help', help=\"Show this help message and exit.\", ) def run_main()",
"os import sys from argparse import _SubParsersAction from argparse import HelpFormatter from typing",
"= args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location) if not os.path.isdir(log_location): print(f'The",
"help='Set a new filename for the logger.', ) config_subparser_logging.add_argument( '-l', nargs='?', metavar='pathname', dest='log_location',",
"off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set a new filename for the",
"= __build_parser() argv = argv[1:] args = main_parser.parse_args(args=argv) # triggering config subparser if",
") add_parser_help(main_parser) # ---- configuration structured as subparser ----- config_subparsers = main_parser.add_subparsers( title='log",
"files/dirs containing the pattern are renamed.', ) main_parser.add_argument( '-e', metavar='except_pattern', dest='except_pattern', nargs='?', action='store',",
"dest='set_search_value', help=\"Set a new 'search-value' permanently.\", ) config_subparser_renaming.add_argument( '-n', nargs='?', metavar='new_value', dest='set_new_value', help=\"Set",
"are also returned. :returns Tuples containing the number of directories, files and the",
"= file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name, full_new) if",
"return \"\" return super()._format_action_invocation(action) class MyOwnFormatter(NoSubparsersMetavarFormatter, argparse.RawDescriptionHelpFormatter): \"\"\" Removes metavar of config subparser",
"f\"None of the {len(all_selected_files_dirs)} present files/directories contain the search value '{SEARCH_VALUE}'!\" print(searchval_msg) return",
"config.get('VALUE-SETTINGS', 'new_value') if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE = ''",
") main_parser.add_argument( '-n', dest='new_value', nargs='?', action='store', metavar='new_value', help=\"Define custom new-value (default: '_').\" )",
"'-i', '--immediately', action='store_true', help='Skip security question, renaming preview and execute immediately.', ) main_parser.add_argument(",
"files_dirs.extend(args.file_or_dir) if args.recursive: files_dirs = recurse_dirs_and_files() # sort paths (longest paths first) so",
"custom new-value (default: '_').\" ) main_parser.add_argument( '-p', dest='pattern_only', nargs='?', action='store', metavar='pattern_only', help='Only files/dirs",
"'new_value') if NEW_VALUE == \"''\" or NEW_VALUE == '\"\"': NEW_VALUE = '' filecount,",
"and directory names within your current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make",
"all_files_dirs.append(rel_dirpath) return all_files_dirs # hack for removing the metavar below the subparsers (config)",
"old_logger_path = get_logger_path() log_location = args.log_location if '~' in args.log_location: log_location = os.path.expanduser(args.log_location)",
"directory are mapped into a list. :returns List of all file/directory paths, recursively",
"------ files-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and",
"for configuring spasco. \"\"\" config_subparser = sub_parsers.add_parser( name='config', description='search-value and new-value can be",
"import configparser import fnmatch import logging import os import sys from argparse import",
"files/directories within the current working directory are mapped into a list. :returns List",
"not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x) if",
"computer-friendly 😄', formatter_class=lambda prog: MyOwnFormatter( prog, max_help_position=80, ), ) # optional arguments: main_parser.add_argument(",
"args.search_value if args.search_value else config.get( 'VALUE-SETTINGS', 'search_value', ) if SEARCH_VALUE == \"' '\":",
"{config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: \"\"\"",
"deepest nested file/directory: files_dirs = [x.split('/') for x in files_dirs] sorted_paths = sorted(files_dirs,",
"path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount} files and",
"dest='log_location', help='Set a new file location for the logger.', ) config_subparser_renaming = config_subparser.add_argument_group(",
"# ------ except-pattern filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.except_pattern",
"print(f\"'{before_renaming}'{' ' * (max([len(x) for x in filtered_paths]) - len(before))} {fmt('🡆', Txt.greenblue)} '{after_renaming}'\",)",
"line arguments. :returns An ArgumentParser instance for the CLI. \"\"\" main_parser = argparse.ArgumentParser(",
"------ no file/dir existent ---- if not files_dirs: print('No directory or file present!')",
"also returned. :returns Tuples containing the number of directories, files and the names",
"OS X / linux\") def main(argv: List[str]) -> int: \"\"\" Main program. :argument",
"help=\"Logging is turned on/off (default: off).\", ) config_subparser_logging.add_argument( '-f', nargs='?', metavar='filename', dest='log_name', help='Set",
"files-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if args.files_only and not",
"for x in files_dirs.copy(): if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not",
"current working directory by \\n' f'underscores.\\n\\nsrc: {__src_url__}', epilog='Make your files more computer-friendly 😄',",
"not config.read(settings_file): config['VALUE-SETTINGS'] = { 'search_value': \"' '\", 'new_value': '_', } config['LOG-SETTINGS'] =",
"logger.', ) config_subparser_renaming = config_subparser.add_argument_group( 'renaming settings', ) config_subparser_renaming.add_argument( '-s', nargs='?', metavar='search_value', dest='set_search_value',",
"and then a logger: config = configparser.ConfigParser() config.read(settings_file) # default values for log",
"# sort paths (longest paths first) so that renaming starts with the deepest",
"bolded=True) after_heading = fmt('After', Txt.blue, bolded=True) sep_line = fmt('──', Txt.greenblue) print(f\"{before_heading} {' '",
"if SEARCH_VALUE not in x.split('/')[-1]: files_dirs.remove(x) if not files_dirs: searchval_msg = f\"None of",
"and not os.path.isdir(x)] for x in files_dirs.copy(): if args.dirs_only and not os.path.isdir(x): files_dirs.remove(x)",
"list (rel to cwd): for dirpath, dirnames, filenames in os.walk(base_path): for filename in",
"for dirname in dirnames: full_dirpath = dirpath + '/' + dirname rel_dirpath =",
"prog=__title__, add_help=False, description=f'Spasco is a glorified replace function. By default it replaces whitespaces\\n'",
"args.except_pattern and fnmatch.fnmatch(os.path.split(x)[-1], args.except_pattern): files_dirs.remove(x) if not files_dirs: print(f'None of the exception-pattern matching",
"default=os.listdir(), help='Select a single file or directory for renaming.', ) main_parser.add_argument( '-s', dest='search_value',",
"1 config['LOG-SETTINGS']['logger_location'] = log_location with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path()",
"[-n [filename]] [-l [pathname]] [-h, --help ]', add_help=False, formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter( prog, max_help_position=33,",
"directories.', ) main_parser.add_argument( '-i', '--immediately', action='store_true', help='Skip security question, renaming preview and execute",
"'w') as fp: config.write(fp) print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')!r}.\",) return 0 if",
"metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file or directory for renaming.', )",
"print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value: {config.get('VALUE-SETTINGS', 'search_value')}",
"int: \"\"\" Boolean logic of config subparser triggering. \"\"\" args = config_subparser.parse_args(argv[1:]) if",
"os.path.split(old_path_name) new_name = file.replace(search_value, new_value) full_new = os.path.join(path_base, new_name) renamed_paths.append(full_new) if renaming: os.rename(old_path_name,",
"the search-value {SEARCH_VALUE!r}.',) return 1 # ------ dirs-only filter ----- # [files_dirs.remove(x) for",
"print(f\"{__title__!r} is currently not optimized for platforms other than OS X / linux\")",
"{config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] = args.set_new_value with open(settings_file, 'w') as",
"names returned. Furthermore, the number fo directories/files which were renamed are also returned.",
"'w') as fp: config.write(fp) new_logger_path = get_logger_path() os.rename(old_logger_path, new_logger_path) print(f\"The new log location",
"for x in files_dirs] sorted_paths = sorted(files_dirs, key=len, reverse=True) files_dirs = ['/'.join(path_as_lst) for",
"renamed! ✨💄✨', Txt.greenblue) print(success_msg) return 0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg",
"Tuple from spasco import __src_url__ from spasco import __title__ from spasco import __version__",
"files_dirs.remove(x) if not files_dirs: print(f'None of the {len(all_selected_files_dirs)} present files/directories contain the pattern",
"help='Returns your current settings for logging and renaming.', ) add_parser_help(config_subparser) config_subparser_logging = config_subparser.add_argument_group(",
"of the {len(all_selected_files_dirs)} present files/directories contain the pattern {args.pattern_only!r}!') return 1 # ------",
"\"-t\", dest='file_or_dir', metavar='file_or_dir', action='store', nargs='?', default=os.listdir(), help='Select a single file or directory for",
"spasco.term_color import Txt base, file = os.path.split(__file__) settings_file = os.path.join(base, 'settings.ini') # set",
"__src_url__ from spasco import __title__ from spasco import __version__ from spasco.term_color import fmt",
"1 # ------ dirs-only filter ----- # [files_dirs.remove(x) for x in files_dirs.copy() if",
"######################## # 2: path filtration # ######################## SEARCH_VALUE = args.search_value if args.search_value else",
"'config': execute_config(config_subparser, argv) return 0 ########################### # 1 select and sort paths #",
"config.write(fp) print(f\"The new 'new-value' is {config.get('VALUE-SETTINGS', 'new_value')}.\") return 0 if args.set_new_value: config['VALUE-SETTINGS']['new_value'] =",
"get_logger_path() config['LOG-SETTINGS']['logger_filename'] = args.log_name with open(settings_file, 'w') as fp: config.write(fp) new_logger_path = get_logger_path()",
"filter ------ # [files_dirs.remove(x) for x in files_dirs.copy() if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1],",
"dirname in dirnames: full_dirpath = dirpath + '/' + dirname rel_dirpath = os.path.relpath(full_dirpath,",
"print(f\"The new search-value is {config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w')",
"return 1 # ------ search-value filter ------ # [files_dirs.remove(x) for x in all_selected_files_dirs",
"0 else: print(fmt(\"Command aborted.\", textcolor=Txt.pink)) return 1 settings_msg = f\"\"\"{fmt(\"value settings:\", Txt.greenblue)} search_value:",
"are renamed.', ) main_parser.add_argument( '-f', '--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument(",
"sys.exit(main(sys.argv)) except Exception as e: sys.stderr.write(__title__ + ': ' + str(e) + '\\n')",
"args.new_value: NEW_VALUE = args.new_value if args.new_value is None: NEW_VALUE = config.get('VALUE-SETTINGS', 'new_value') if",
"'logging_turned_on')} logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) ->",
"NoSubparsersMetavarFormatter(HelpFormatter): def _format_action_invocation(self, action): # type: ignore if isinstance(action, _SubParsersAction): return \"\" return",
"{config.get('VALUE-SETTINGS', 'search_value')}.\",) else: config['VALUE-SETTINGS']['search_value'] = args.set_search_value with open(settings_file, 'w') as fp: config.write(fp) print(f\"The",
"if vars(args).get('command', None) == 'config': execute_config(config_subparser, argv) return 0 ########################### # 1 select",
"logger_filename: {config.get('LOG-SETTINGS', 'logger_filename')} logger_location: {config.get('LOG-SETTINGS', 'logger_location')}\"\"\" def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int:",
"new_pathnames = path_renaming( path_lst=filtered_paths, search_value=SEARCH_VALUE, new_value=NEW_VALUE, renaming=True, ) success_msg = fmt(f'All done! {filecount}",
"'--files-only', action='store_true', help='Only files are renamed.', ) main_parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into",
"if args.pattern_only and not fnmatch.fnmatch(os.path.split(x)[1], args.pattern_only): files_dirs.remove(x) if not files_dirs: print(f'None of the"
] |
[] |
[
"App import create_app # 初始化模块 manager = create_app() if __name__ == '__main__': manager.run()",
"<filename>flask-proj/manage.py<gh_stars>0 from App import create_app # 初始化模块 manager = create_app() if __name__ ==",
"from App import create_app # 初始化模块 manager = create_app() if __name__ == '__main__':"
] |
[
"track in m ], axis = 2) # return stacked tracks note matrix",
"if self.import_list[index] is None: # import data to memory self.import_data(index) # return data",
"data track.append(note) # store track notes tracks.append(track) # return extracted midi tracks return",
"in self.file_names ] # case filter by key if False: # get index",
"stack on new axis M = np.stack([ np.pad(track, ((0, 0), (0, s -",
"/= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples += EPSILON / 2 return",
"samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples += EPSILON /",
"= [ name for name in os.listdir(dir_path) if 'mid' in name[-4:] ] #",
"[ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] # case filter by key",
"for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index =",
"m ], axis = 2) # return stacked tracks note matrix return M",
"for import state if self.import_list[index] is None: # import data to memory self.import_data(index)",
"''' def linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples)",
"> 3 ] # filter midi file and file name lists self.midi_files =",
"for name in os.listdir(dir_path) if 'mid' in name[-4:] ] # import and store",
"in j ] self.file_names = [ self.file_names[i] for i in j ] #",
"range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index = seq_begin + self.seq_len",
"def __init__(self, dir_path: str, cache = False, ds: int = 20): ''' init",
"False, ds: int = 20): ''' init dataset, import midi files ''' super().__init__()",
"ds # get and store list midi files in directory self.file_names = [",
"matrix melody = self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds] # store",
"convert tracks to matrix ''' # initialise track matricies list m = []",
"i in j ] # init store of import state self.import_list = [",
"sequences = batch[:, from_index : to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences",
"range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: #",
"note tracks matrix matrix = self.tracks2matrix(tracks) # get melody format from matrix melody",
"initialise track matricies list m = [] # iterate tracks for track in",
"tracks.append(track) # return extracted midi tracks return tracks def tracks2matrix(self, tracks: list): '''",
"vector by index N[int(msg['note'])] = int(msg['velocity']) # store track note matrix m.append(M) #",
"index midi = self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi) # get",
"(excl. meta track, extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for i",
"np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note, time) where nonzero j =",
"meta track, extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for i in",
"track for msg in midi.tracks[i][:]: # ensure note data only if msg.type in",
"list m = [] # iterate tracks for track in tracks: # initialise",
"target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset = False def",
"note = {} # store each note data #note['type'] = msg.type #note['channel'] =",
"# array handling import numpy as np # midi file import and parse",
"tracks j = [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3",
"= [0] else: ts = range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl.",
"import list self.import_list[index] = melody def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile",
"matrix ''' # get track note matrix for melody only M = matrix[:,:,0]",
"def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len",
"self.file_names = [ self.file_names[i] for i in j ] # init store of",
"of note vector by index N[int(msg['note'])] = int(msg['velocity']) # store track note matrix",
"EPSILON samples += EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float()",
"# iterate through midi files for index in range(len(self.file_names)): # import data to",
"ts = range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl. meta track, extra),",
"file name lists self.midi_files = [ self.midi_files[i] for i in j ] self.file_names",
"dataset class for midi files ''' def __init__(self, dir_path: str, cache = False,",
"note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type == 'note_off'",
"None: # import data to memory self.import_data(index) # return data if already imported",
"s - track.shape[1]))) for track in m ], axis = 2) # return",
"] # filter midi file and file name lists self.midi_files = [ self.midi_files[i]",
"[] if len(midi.tracks) == 1: ts = [0] else: ts = range(len(midi.tracks))[1:4] #",
"samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples += EPSILON / 2",
"name[-4:] ] # import and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name))",
"return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset,",
"MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files ''' def __init__(self, dir_path: str, cache",
"ts: # store track data as dict for processing track = [] #",
"track.append(note) # store track notes tracks.append(track) # return extracted midi tracks return tracks",
"# initialise track matricies list m = [] # iterate tracks for track",
"tracks2matrix(self, tracks: list): ''' convert tracks to matrix ''' # initialise track matricies",
"store note data track.append(note) # store track notes tracks.append(track) # return extracted midi",
"state vector, 7-bit note depth N = np.zeros(128, dtype = np.int16) # initialise",
"tracks to matrix ''' # initialise track matricies list m = [] #",
"in import list self.import_list[index] = melody def midi2tracks(self, midi): ''' extract tracks from",
"matricies list m = [] # iterate tracks for track in tracks: #",
"over tracks in midi (excl. meta track, extra), [melody, chords, bass] #for i",
"chords, bass] #for i in range(len(midi.tracks))[1:4]: for i in ts: # store track",
"''' import midi data to memory ''' # get midi by index midi",
"self.seq_len sequences = batch[:, from_index : to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape)",
"in m ]) # pad tracks to max length of time axis, stack",
"# ensure note data only if msg.type in ['note_on', 'note_off']: # init note",
"matrix M = np.concatenate( [M, n], axis = 1 ) # update value",
"midi by index midi = self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi)",
"np.stack([ N for _ in range( int(msg['time']) ) ]).T # append note state",
"*= q_levels - EPSILON samples += EPSILON / 2 return samples.long() def linear_dequantize(samples,",
"index (note, time) where nonzero j = np.where( M != 0 ) #",
"= ds # get and store list midi files in directory self.file_names =",
"for processing track = [] # iterate messages in track for msg in",
"track note matrix (zero init column) M = np.zeros((128, 1), dtype = np.int16)",
"1: ts = [0] else: ts = range(len(midi.tracks))[1:4] # iterate over tracks in",
"def tracks2matrix(self, tracks: list): ''' convert tracks to matrix ''' # initialise track",
"i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter midi file and",
"import data to memory self.import_data(index) # return data if already imported return self.import_list[index]",
"else 1 # store note data track.append(note) # store track notes tracks.append(track) #",
"def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile ''' # initialise tracks list",
"if 'mid' in name[-4:] ] # import and store midi files self.midi_files =",
"#for i in range(len(midi.tracks))[1:4]: for i in ts: # store track data as",
"== 1: ts = [0] else: ts = range(len(midi.tracks))[1:4] # iterate over tracks",
"track note matrix M = np.concatenate( [M, n], axis = 1 ) #",
"- track.shape[1]))) for track in m ], axis = 2) # return stacked",
"matrix return M def matrix2melody(self, matrix): ''' extract melody from note matrix '''",
"q_zero(q_levels): return q_levels // 2 ''' def __len__(self): ''' return total midi files",
"self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size,",
"tracks def tracks2matrix(self, tracks: list): ''' convert tracks to matrix ''' # initialise",
"def linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2) - 1 def q_zero(q_levels):",
"super().__init__() # store downsampling factor self.ds = ds # get and store list",
"melody def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile ''' # initialise tracks",
"track data as dict for processing track = [] # iterate messages in",
"melody, default negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index",
"# if time step changes, store intermediate notes if int(msg['time']) != 0: #",
"where nonzero j = np.where( M != 0 ) # set melody note",
"cache: # iterate through midi files for index in range(len(self.file_names)): # import data",
"''' extract tracks from mido.MidiFile ''' # initialise tracks list tracks = []",
"msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] = 0",
"bass] #for i in range(len(midi.tracks))[1:4]: for i in ts: # store track data",
"msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type == 'note_off' else 1",
"melody[j[1]] = j[0] # return extracted melody return melody def __getitem__(self, index): '''",
"[melody, chords, bass] tracks j = [ i for i in range(len(self.file_names)) if",
"] if False: # get index for only midi with meta plus [melody,",
"bass] tracks j = [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) >",
"] # case filter by key if False: # get index for only",
"''' # initialise track matricies list m = [] # iterate tracks for",
"and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get index for only midi",
"memory self.import_data(index) # return data if already imported return self.import_list[index] ''' def linear_quantize(samples,",
"# iterate tracks for track in tracks: # initialise note state vector, 7-bit",
"self.file_names ] # case filter by key if False: # get index for",
"as dict for processing track = [] # iterate messages in track for",
"init column) M = np.zeros((128, 1), dtype = np.int16) # iterate messages in",
"index): ''' return tracks note matrix ''' # check for import state if",
"= melody[::self.ds] # store matrix in import list self.import_list[index] = melody def midi2tracks(self,",
"from matrix melody = self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds] #",
"return number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size,",
"if len(midi.tracks) == 1: ts = [0] else: ts = range(len(midi.tracks))[1:4] # iterate",
"] self.file_names = [ self.file_names[i] for i in j ] # init store",
"[ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in",
"over range time step n = np.stack([ N for _ in range( int(msg['time'])",
"and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi",
"int(msg['velocity']) # store track note matrix m.append(M) # get max length track s",
"by index melody[j[1]] = j[0] # return extracted melody return melody def __getitem__(self,",
"if msg.type in ['note_on', 'note_off']: # init note data dict note = {}",
"class for midi files ''' def __init__(self, dir_path: str, cache = False, ds:",
"midi files ''' super().__init__() # store downsampling factor self.ds = ds # get",
"index in range(len(self.file_names)): # import data to memory self.import_data(index) def import_data(self, index): '''",
"msg.velocity note['velocity'] = 0 if msg.type == 'note_off' else 1 # store note",
"store downsampling factor self.ds = ds # get and store list midi files",
"melody note at time by index melody[j[1]] = j[0] # return extracted melody",
"chords, bass] tracks j = [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks)",
"import data to memory self.import_data(index) def import_data(self, index): ''' import midi data to",
"negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note, time)",
"data to memory self.import_data(index) # return data if already imported return self.import_list[index] '''",
"# store track notes tracks.append(track) # return extracted midi tracks return tracks def",
"melody def __getitem__(self, index): ''' return tracks note matrix ''' # check for",
"= [ self.file_names[i] for i in j ] # init store of import",
"''' def __len__(self): ''' return total midi files ''' # return number of",
"factor self.ds = ds # get and store list midi files in directory",
"M = matrix[:,:,0] # init zero melody, default negative one #melody = np.ones(M.shape[1])*-1",
"# import and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name",
"matrix m.append(M) # get max length track s = max([ track.shape[1] for track",
"0), (0, s - track.shape[1]))) for track in m ], axis = 2)",
"in range(len(self.midi_files)) ] # pre-cache all data if cache: # iterate through midi",
"[0] else: ts = range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl. meta",
"midi with meta plus [melody, chords, bass] tracks j = [ i for",
"self.import_list = [ None for _ in range(len(self.midi_files)) ] # pre-cache all data",
"in range( int(msg['time']) ) ]).T # append note state vector to track note",
"# init note data dict note = {} # store each note data",
"= msg.velocity note['velocity'] = 0 if msg.type == 'note_off' else 1 # store",
"msg.type == 'note_off' else 1 # store note data track.append(note) # store track",
"midi tracks tracks = self.midi2tracks(midi) # get note tracks matrix matrix = self.tracks2matrix(tracks)",
"''' return total midi files ''' # return number of midi files return",
"file import and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class",
"midi file and file name lists self.midi_files = [ self.midi_files[i] for i in",
"= np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note, time) where nonzero j",
"import state self.import_list = [ None for _ in range(len(self.midi_files)) ] # pre-cache",
"melody = self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds] # store matrix",
"dtype = np.int16) # iterate messages in track for msg in track: #",
"parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files",
"matrix for melody only M = matrix[:,:,0] # init zero melody, default negative",
"one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note, time) where",
"# store track data as dict for processing track = [] # iterate",
"'note_off']: # init note data dict note = {} # store each note",
"track.shape[1] for track in m ]) # pad tracks to max length of",
"= np.zeros((128, 1), dtype = np.int16) # iterate messages in track for msg",
"initialise note state vector, 7-bit note depth N = np.zeros(128, dtype = np.int16)",
"def linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples",
"self.ds = ds # get and store list midi files in directory self.file_names",
"iterate messages in track for msg in track: # if time step changes,",
"[ self.file_names[i] for i in j ] # init store of import state",
"list midi files in directory self.file_names = [ name for name in os.listdir(dir_path)",
"!= 0 ) # set melody note at time by index melody[j[1]] =",
"case filter by key if False: # get index for only midi with",
"processing track = [] # iterate messages in track for msg in midi.tracks[i][:]:",
"track s = max([ track.shape[1] for track in m ]) # pad tracks",
"i in range(len(midi.tracks))[1:4]: for i in ts: # store track data as dict",
"matrix): ''' extract melody from note matrix ''' # get track note matrix",
"def __len__(self): ''' return total midi files ''' # return number of midi",
"note matrix M = np.concatenate( [M, n], axis = 1 ) # update",
"import state if self.import_list[index] is None: # import data to memory self.import_data(index) #",
"seq_begin - self.overlap_len to_index = seq_begin + self.seq_len sequences = batch[:, from_index :",
"new axis M = np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1]))) for",
"in m ], axis = 2) # return stacked tracks note matrix return",
"melody = np.zeros(M.shape[1]) # get index (note, time) where nonzero j = np.where(",
"[M, n], axis = 1 ) # update value of note vector by",
"samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2) - 1 def",
"axis = 1 ) # update value of note vector by index N[int(msg['note'])]",
"samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels -",
"track note matrix for melody only M = matrix[:,:,0] # init zero melody,",
"i in j ] self.file_names = [ self.file_names[i] for i in j ]",
"# downsample over time melody = melody[::self.ds] # store matrix in import list",
"pad tracks to max length of time axis, stack on new axis M",
"msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type ==",
"int = 20): ''' init dataset, import midi files ''' super().__init__() # store",
"n = np.stack([ N for _ in range( int(msg['time']) ) ]).T # append",
"number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len,",
"def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset = True",
"np.int16) # initialise track note matrix (zero init column) M = np.zeros((128, 1),",
"''' # initialise tracks list tracks = [] if len(midi.tracks) == 1: ts",
"m.append(M) # get max length track s = max([ track.shape[1] for track in",
"''' # filesystem management import os # tensors and nn modules import torch",
"to memory ''' # get midi by index midi = self.midi_files[index] # get",
"extracted melody return melody def __getitem__(self, index): ''' return tracks note matrix '''",
"= msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type",
"init zero melody, default negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) #",
"/ 2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2)",
"# initialise note state vector, 7-bit note depth N = np.zeros(128, dtype =",
"midi2tracks(self, midi): ''' extract tracks from mido.MidiFile ''' # initialise tracks list tracks",
"#note['channel'] = msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity']",
"M = np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1]))) for track in",
"update value of note vector by index N[int(msg['note'])] = int(msg['velocity']) # store track",
"for i in j ] # init store of import state self.import_list =",
"*args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self): for batch in",
"= 2) # return stacked tracks note matrix return M def matrix2melody(self, matrix):",
"[ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter",
"downsampling factor self.ds = ds # get and store list midi files in",
"tracks = self.midi2tracks(midi) # get note tracks matrix matrix = self.tracks2matrix(tracks) # get",
"''' # get track note matrix for melody only M = matrix[:,:,0] #",
"only midi with meta plus [melody, chords, bass] tracks j = [ i",
") # update value of note vector by index N[int(msg['note'])] = int(msg['velocity']) #",
"**kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self):",
"- EPSILON samples += EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels): return",
"tracks tracks = self.midi2tracks(midi) # get note tracks matrix matrix = self.tracks2matrix(tracks) #",
"# initialise tracks list tracks = [] if len(midi.tracks) == 1: ts =",
"imports ''' # filesystem management import os # tensors and nn modules import",
"in directory self.file_names = [ name for name in os.listdir(dir_path) if 'mid' in",
"for msg in track: # if time step changes, store intermediate notes if",
"default negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note,",
"and nn modules import torch # array handling import numpy as np #",
"get note tracks matrix matrix = self.tracks2matrix(tracks) # get melody format from matrix",
"by index N[int(msg['note'])] = int(msg['velocity']) # store track note matrix m.append(M) # get",
"= np.zeros(M.shape[1]) # get index (note, time) where nonzero j = np.where( M",
"def q_zero(q_levels): return q_levels // 2 ''' def __len__(self): ''' return total midi",
"# get track note matrix for melody only M = matrix[:,:,0] # init",
"time by index melody[j[1]] = j[0] # return extracted melody return melody def",
"track matricies list m = [] # iterate tracks for track in tracks:",
"[ None for _ in range(len(self.midi_files)) ] # pre-cache all data if cache:",
"of time axis, stack on new axis M = np.stack([ np.pad(track, ((0, 0),",
"meta plus [melody, chords, bass] tracks j = [ i for i in",
"''' super().__init__() # store downsampling factor self.ds = ds # get and store",
"False: # get index for only midi with meta plus [melody, chords, bass]",
"track in tracks: # initialise note state vector, 7-bit note depth N =",
"seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len =",
"= seq_len self.overlap_len = overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples)",
"store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ]",
"matrix (zero init column) M = np.zeros((128, 1), dtype = np.int16) # iterate",
"state self.import_list = [ None for _ in range(len(self.midi_files)) ] # pre-cache all",
"note matrix return M def matrix2melody(self, matrix): ''' extract melody from note matrix",
"s = max([ track.shape[1] for track in m ]) # pad tracks to",
"to memory self.import_data(index) def import_data(self, index): ''' import midi data to memory '''",
"['note_on', 'note_off']: # init note data dict note = {} # store each",
"- 1 def q_zero(q_levels): return q_levels // 2 ''' def __len__(self): ''' return",
"# get and store list midi files in directory self.file_names = [ name",
"range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl. meta track, extra), [melody, chords,",
"state vector over range time step n = np.stack([ N for _ in",
"value of note vector by index N[int(msg['note'])] = int(msg['velocity']) # store track note",
"matrix matrix = self.tracks2matrix(tracks) # get melody format from matrix melody = self.matrix2melody(matrix)",
"#print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin -",
"def matrix2melody(self, matrix): ''' extract melody from note matrix ''' # get track",
"note state vector over range time step n = np.stack([ N for _",
"in midi.tracks[i][:]: # ensure note data only if msg.type in ['note_on', 'note_off']: #",
"# return extracted melody return melody def __getitem__(self, index): ''' return tracks note",
"mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files ''' def",
"iterate through midi files for index in range(len(self.file_names)): # import data to memory",
"range(len(self.file_names)): # import data to memory self.import_data(index) def import_data(self, index): ''' import midi",
"note['velocity'] = 0 if msg.type == 'note_off' else 1 # store note data",
"of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len,",
"# case filter by key if False: # get index for only midi",
"# check for import state if self.import_list[index] is None: # import data to",
"EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels /",
"if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get",
"time melody = melody[::self.ds] # store matrix in import list self.import_list[index] = melody",
"#melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get index (note, time) where nonzero",
"# return number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset,",
"tracks to max length of time axis, stack on new axis M =",
"q_levels): return samples.float() / (q_levels / 2) - 1 def q_zero(q_levels): return q_levels",
"if len(self.midi_files[i].tracks) > 3 ] # filter midi file and file name lists",
"for melody only M = matrix[:,:,0] # init zero melody, default negative one",
"(q_levels / 2) - 1 def q_zero(q_levels): return q_levels // 2 ''' def",
"intermediate notes if int(msg['time']) != 0: # extend note state vector over range",
"!= 0: # extend note state vector over range time step n =",
"midi (excl. meta track, extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for",
"for msg in midi.tracks[i][:]: # ensure note data only if msg.type in ['note_on',",
"''' # check for import state if self.import_list[index] is None: # import data",
"str(self.midi_files[i].tracks[0][2]) ] if False: # get index for only midi with meta plus",
"state if self.import_list[index] is None: # import data to memory self.import_data(index) # return",
"self.import_list[index] = melody def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile ''' #",
"files in directory self.file_names = [ name for name in os.listdir(dir_path) if 'mid'",
"management import os # tensors and nn modules import torch # array handling",
"''' extract melody from note matrix ''' # get track note matrix for",
"= [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] # case filter by",
"1 ) # update value of note vector by index N[int(msg['note'])] = int(msg['velocity'])",
"in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False:",
"for midi files ''' def __init__(self, dir_path: str, cache = False, ds: int",
"store intermediate notes if int(msg['time']) != 0: # extend note state vector over",
"note data dict note = {} # store each note data #note['type'] =",
"tracks: list): ''' convert tracks to matrix ''' # initialise track matricies list",
"step changes, store intermediate notes if int(msg['time']) != 0: # extend note state",
"already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone() samples -=",
"]) # pad tracks to max length of time axis, stack on new",
"torch # array handling import numpy as np # midi file import and",
"= sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset = False def __len__(self):",
"''' # get midi by index midi = self.midi_files[index] # get midi tracks",
"= self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds] # store matrix in",
"for index in range(len(self.file_names)): # import data to memory self.import_data(index) def import_data(self, index):",
"= np.int16) # initialise track note matrix (zero init column) M = np.zeros((128,",
"to_index = seq_begin + self.seq_len sequences = batch[:, from_index : to_index] input_sequences =",
"range(len(self.midi_files)) ] # pre-cache all data if cache: # iterate through midi files",
"iterate over tracks in midi (excl. meta track, extra), [melody, chords, bass] #for",
"# initialise track note matrix (zero init column) M = np.zeros((128, 1), dtype",
"# get midi tracks tracks = self.midi2tracks(midi) # get note tracks matrix matrix",
"cache = False, ds: int = 20): ''' init dataset, import midi files",
"__len__(self): ''' return total midi files ''' # return number of midi files",
"self.import_data(index) # return data if already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels):",
"q_levels - EPSILON samples += EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels):",
"track, extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for i in ts:",
"vector to track note matrix M = np.concatenate( [M, n], axis = 1",
"if False: # get index for only midi with meta plus [melody, chords,",
"data only if msg.type in ['note_on', 'note_off']: # init note data dict note",
"= [] # iterate tracks for track in tracks: # initialise note state",
"j[0] # return extracted melody return melody def __getitem__(self, index): ''' return tracks",
"files ''' # return number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def",
"handling import numpy as np # midi file import and parse from mido",
"note matrix m.append(M) # get max length track s = max([ track.shape[1] for",
"in track for msg in track: # if time step changes, store intermediate",
"= self.tracks2matrix(tracks) # get melody format from matrix melody = self.matrix2melody(matrix) # downsample",
"get index for only midi with meta plus [melody, chords, bass] tracks j",
"for i in j ] self.file_names = [ self.file_names[i] for i in j",
"# extend note state vector over range time step n = np.stack([ N",
"in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter midi file and file",
"for track in tracks: # initialise note state vector, 7-bit note depth N",
"store track note matrix m.append(M) # get max length track s = max([",
"return tracks note matrix ''' # check for import state if self.import_list[index] is",
"dataset, import midi files ''' super().__init__() # store downsampling factor self.ds = ds",
"= j[0] # return extracted melody return melody def __getitem__(self, index): ''' return",
"self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /=",
"# iterate over tracks in midi (excl. meta track, extra), [melody, chords, bass]",
"note vector by index N[int(msg['note'])] = int(msg['velocity']) # store track note matrix m.append(M)",
"extend note state vector over range time step n = np.stack([ N for",
"in midi (excl. meta track, extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]:",
"[ self.midi_files[i] for i in j ] self.file_names = [ self.file_names[i] for i",
"__init__(self, dir_path: str, cache = False, ds: int = 20): ''' init dataset,",
"# init store of import state self.import_list = [ None for _ in",
"melody = melody[::self.ds] # store matrix in import list self.import_list[index] = melody def",
"files for index in range(len(self.file_names)): # import data to memory self.import_data(index) def import_data(self,",
"iterate messages in track for msg in midi.tracks[i][:]: # ensure note data only",
"#note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type == 'note_off' else 1 #",
"notes if int(msg['time']) != 0: # extend note state vector over range time",
"np.where( M != 0 ) # set melody note at time by index",
"= [ self.midi_files[i] for i in j ] self.file_names = [ self.file_names[i] for",
"directory self.file_names = [ name for name in os.listdir(dir_path) if 'mid' in name[-4:]",
"dict for processing track = [] # iterate messages in track for msg",
"all data if cache: # iterate through midi files for index in range(len(self.file_names)):",
"overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len",
"note at time by index melody[j[1]] = j[0] # return extracted melody return",
"imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples)",
"extra), [melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for i in ts: #",
"] # import and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for",
"column) M = np.zeros((128, 1), dtype = np.int16) # iterate messages in track",
"# get index (note, time) where nonzero j = np.where( M != 0",
"os.listdir(dir_path) if 'mid' in name[-4:] ] # import and store midi files self.midi_files",
"_ in range(len(self.midi_files)) ] # pre-cache all data if cache: # iterate through",
"initialise track note matrix (zero init column) M = np.zeros((128, 1), dtype =",
"note matrix ''' # get track note matrix for melody only M =",
"// 2 ''' def __len__(self): ''' return total midi files ''' # return",
"midi = self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi) # get note",
"note data #note['type'] = msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time'] =",
"plus [melody, chords, bass] tracks j = [ i for i in range(len(self.file_names))",
"3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get index for only",
"and store list midi files in directory self.file_names = [ name for name",
"2) # return stacked tracks note matrix return M def matrix2melody(self, matrix): '''",
"init store of import state self.import_list = [ None for _ in range(len(self.midi_files))",
"np.concatenate( [M, n], axis = 1 ) # update value of note vector",
"# get melody format from matrix melody = self.matrix2melody(matrix) # downsample over time",
"ds: int = 20): ''' init dataset, import midi files ''' super().__init__() #",
"= np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1]))) for track in m",
"j ] self.file_names = [ self.file_names[i] for i in j ] # init",
"np.zeros(M.shape[1]) # get index (note, time) where nonzero j = np.where( M !=",
"midi): ''' extract tracks from mido.MidiFile ''' # initialise tracks list tracks =",
"(zero init column) M = np.zeros((128, 1), dtype = np.int16) # iterate messages",
"melody return melody def __getitem__(self, index): ''' return tracks note matrix ''' #",
"# init zero melody, default negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1])",
"overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset =",
"data as dict for processing track = [] # iterate messages in track",
"note['note'] = msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if",
"= 0 if msg.type == 'note_off' else 1 # store note data track.append(note)",
"for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter midi file",
"ensure note data only if msg.type in ['note_on', 'note_off']: # init note data",
"in track for msg in midi.tracks[i][:]: # ensure note data only if msg.type",
"for _ in range( int(msg['time']) ) ]).T # append note state vector to",
"by key if False: # get index for only midi with meta plus",
"name lists self.midi_files = [ self.midi_files[i] for i in j ] self.file_names =",
"i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2])",
"matrix in import list self.import_list[index] = melody def midi2tracks(self, midi): ''' extract tracks",
"in os.listdir(dir_path) if 'mid' in name[-4:] ] # import and store midi files",
"np # midi file import and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset):",
"self.tracks2matrix(tracks) # get melody format from matrix melody = self.matrix2melody(matrix) # downsample over",
"track = [] # iterate messages in track for msg in midi.tracks[i][:]: #",
"melody from note matrix ''' # get track note matrix for melody only",
"length of time axis, stack on new axis M = np.stack([ np.pad(track, ((0,",
"(note, time) where nonzero j = np.where( M != 0 ) # set",
"((0, 0), (0, s - track.shape[1]))) for track in m ], axis =",
"tensors and nn modules import torch # array handling import numpy as np",
"def __getitem__(self, index): ''' return tracks note matrix ''' # check for import",
"'mid' in name[-4:] ] # import and store midi files self.midi_files = [",
"(0, s - track.shape[1]))) for track in m ], axis = 2) #",
"m = [] # iterate tracks for track in tracks: # initialise note",
"range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter midi file and file name",
"set melody note at time by index melody[j[1]] = j[0] # return extracted",
"note data only if msg.type in ['note_on', 'note_off']: # init note data dict",
"file_name in self.file_names ] # case filter by key if False: # get",
"from note matrix ''' # get track note matrix for melody only M",
"return tracks def tracks2matrix(self, tracks: list): ''' convert tracks to matrix ''' #",
"axis = 2) # return stacked tracks note matrix return M def matrix2melody(self,",
"self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index",
"note depth N = np.zeros(128, dtype = np.int16) # initialise track note matrix",
"# store track note matrix m.append(M) # get max length track s =",
"os # tensors and nn modules import torch # array handling import numpy",
"n], axis = 1 ) # update value of note vector by index",
"return M def matrix2melody(self, matrix): ''' extract melody from note matrix ''' #",
"-= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples += EPSILON",
"seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index = seq_begin",
"self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset = False def __len__(self): raise NotImplementedError()",
"list self.import_list[index] = melody def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile '''",
"], axis = 2) # return stacked tracks note matrix return M def",
"= matrix[:,:,0] # init zero melody, default negative one #melody = np.ones(M.shape[1])*-1 melody",
"return melody def __getitem__(self, index): ''' return tracks note matrix ''' # check",
"= self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi) # get note tracks",
"self.import_data(index) def import_data(self, index): ''' import midi data to memory ''' # get",
"= np.zeros(128, dtype = np.int16) # initialise track note matrix (zero init column)",
"sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences)",
"samples += EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float() /",
"file and file name lists self.midi_files = [ self.midi_files[i] for i in j",
"from_index : to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len",
"array handling import numpy as np # midi file import and parse from",
"''' convert tracks to matrix ''' # initialise track matricies list m =",
"by index midi = self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi) #",
"numpy as np # midi file import and parse from mido import MidiFile",
"= seq_begin - self.overlap_len to_index = seq_begin + self.seq_len sequences = batch[:, from_index",
"len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get index",
"if msg.type == 'note_off' else 1 # store note data track.append(note) # store",
"filesystem management import os # tensors and nn modules import torch # array",
"-1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset =",
"samples.float() / (q_levels / 2) - 1 def q_zero(q_levels): return q_levels // 2",
"M = np.concatenate( [M, n], axis = 1 ) # update value of",
"step n = np.stack([ N for _ in range( int(msg['time']) ) ]).T #",
"to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield",
"tracks = [] if len(midi.tracks) == 1: ts = [0] else: ts =",
"np.pad(track, ((0, 0), (0, s - track.shape[1]))) for track in m ], axis",
"downsample over time melody = melody[::self.ds] # store matrix in import list self.import_list[index]",
"msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity'] = msg.velocity",
"return samples.float() / (q_levels / 2) - 1 def q_zero(q_levels): return q_levels //",
"in j ] # init store of import state self.import_list = [ None",
"import and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in",
"self.midi2tracks(midi) # get note tracks matrix matrix = self.tracks2matrix(tracks) # get melody format",
"batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self): for batch",
"and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names",
"note data track.append(note) # store track notes tracks.append(track) # return extracted midi tracks",
"samples *= q_levels - EPSILON samples += EPSILON / 2 return samples.long() def",
"format from matrix melody = self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds]",
"range time step n = np.stack([ N for _ in range( int(msg['time']) )",
"note matrix ''' # check for import state if self.import_list[index] is None: #",
"= {} # store each note data #note['type'] = msg.type #note['channel'] = msg.channel",
"= range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl. meta track, extra), [melody,",
"= msg.time #note['velocity'] = msg.velocity note['velocity'] = 0 if msg.type == 'note_off' else",
"each note data #note['type'] = msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time']",
"m ]) # pad tracks to max length of time axis, stack on",
"+ self.seq_len sequences = batch[:, from_index : to_index] input_sequences = sequences[:, : -1]",
"midi files ''' def __init__(self, dir_path: str, cache = False, ds: int =",
"2 ''' def __len__(self): ''' return total midi files ''' # return number",
"# filesystem management import os # tensors and nn modules import torch #",
"midi.tracks[i][:]: # ensure note data only if msg.type in ['note_on', 'note_off']: # init",
"memory ''' # get midi by index midi = self.midi_files[index] # get midi",
"for only midi with meta plus [melody, chords, bass] tracks j = [",
"in ['note_on', 'note_off']: # init note data dict note = {} # store",
"M def matrix2melody(self, matrix): ''' extract melody from note matrix ''' # get",
"#print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset = False",
"initialise tracks list tracks = [] if len(midi.tracks) == 1: ts = [0]",
"axis M = np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1]))) for track",
"filter midi file and file name lists self.midi_files = [ self.midi_files[i] for i",
"depth N = np.zeros(128, dtype = np.int16) # initialise track note matrix (zero",
"i in ts: # store track data as dict for processing track =",
"only if msg.type in ['note_on', 'note_off']: # init note data dict note =",
"batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len",
"tracks note matrix ''' # check for import state if self.import_list[index] is None:",
"# iterate messages in track for msg in track: # if time step",
"self.import_list[index] is None: # import data to memory self.import_data(index) # return data if",
"data #note['type'] = msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time'] = msg.time",
"in track: # if time step changes, store intermediate notes if int(msg['time']) !=",
"class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files ''' def __init__(self, dir_path: str,",
"store list midi files in directory self.file_names = [ name for name in",
"return extracted melody return melody def __getitem__(self, index): ''' return tracks note matrix",
"midi file import and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset",
"get melody format from matrix melody = self.matrix2melody(matrix) # downsample over time melody",
"mido.MidiFile ''' # initialise tracks list tracks = [] if len(midi.tracks) == 1:",
"return data if already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples =",
"with meta plus [melody, chords, bass] tracks j = [ i for i",
"- self.overlap_len to_index = seq_begin + self.seq_len sequences = batch[:, from_index : to_index]",
"track note matrix m.append(M) # get max length track s = max([ track.shape[1]",
"track.shape[1]))) for track in m ], axis = 2) # return stacked tracks",
"dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len",
"0 ) # set melody note at time by index melody[j[1]] = j[0]",
"linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2) - 1 def q_zero(q_levels): return",
"# set melody note at time by index melody[j[1]] = j[0] # return",
"np.zeros((128, 1), dtype = np.int16) # iterate messages in track for msg in",
"matrix ''' # check for import state if self.import_list[index] is None: # import",
"n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len,",
"1 # store note data track.append(note) # store track notes tracks.append(track) # return",
"msg.type in ['note_on', 'note_off']: # init note data dict note = {} #",
"1 def q_zero(q_levels): return q_levels // 2 ''' def __len__(self): ''' return total",
"dtype = np.int16) # initialise track note matrix (zero init column) M =",
"msg in track: # if time step changes, store intermediate notes if int(msg['time'])",
"== 'note_off' else 1 # store note data track.append(note) # store track notes",
"midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args,",
"batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len)",
"tracks matrix matrix = self.tracks2matrix(tracks) # get melody format from matrix melody =",
"matrix = self.tracks2matrix(tracks) # get melody format from matrix melody = self.matrix2melody(matrix) #",
"int(msg['time']) ) ]).T # append note state vector to track note matrix M",
"from_index = seq_begin - self.overlap_len to_index = seq_begin + self.seq_len sequences = batch[:,",
"filter by key if False: # get index for only midi with meta",
"# pad tracks to max length of time axis, stack on new axis",
"q_levels // 2 ''' def __len__(self): ''' return total midi files ''' #",
"for batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples,",
"2) - 1 def q_zero(q_levels): return q_levels // 2 ''' def __len__(self): '''",
"for i in ts: # store track data as dict for processing track",
"input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences,",
"''' # return number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self,",
"i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if",
"if cache: # iterate through midi files for index in range(len(self.file_names)): # import",
"name in os.listdir(dir_path) if 'mid' in name[-4:] ] # import and store midi",
"self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] # case filter",
"M != 0 ) # set melody note at time by index melody[j[1]]",
"class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args,",
"index): ''' import midi data to memory ''' # get midi by index",
"''' imports ''' # filesystem management import os # tensors and nn modules",
"through midi files for index in range(len(self.file_names)): # import data to memory self.import_data(index)",
"melody format from matrix melody = self.matrix2melody(matrix) # downsample over time melody =",
"lists self.midi_files = [ self.midi_files[i] for i in j ] self.file_names = [",
"matrix ''' # initialise track matricies list m = [] # iterate tracks",
": -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset",
"''' def __init__(self, dir_path: str, cache = False, ds: int = 20): '''",
"return total midi files ''' # return number of midi files return len(self.file_names)",
"= np.int16) # iterate messages in track for msg in track: # if",
"in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index = seq_begin +",
"self.file_names[i] for i in j ] # init store of import state self.import_list",
"import midi files ''' super().__init__() # store downsampling factor self.ds = ds #",
"messages in track for msg in track: # if time step changes, store",
"if already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone() samples",
"extract tracks from mido.MidiFile ''' # initialise tracks list tracks = [] if",
"seq_begin + self.seq_len sequences = batch[:, from_index : to_index] input_sequences = sequences[:, :",
"j = np.where( M != 0 ) # set melody note at time",
"append note state vector to track note matrix M = np.concatenate( [M, n],",
"= batch[:, from_index : to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences =",
"= 1 ) # update value of note vector by index N[int(msg['note'])] =",
"# get index for only midi with meta plus [melody, chords, bass] tracks",
"files ''' def __init__(self, dir_path: str, cache = False, ds: int = 20):",
"index for only midi with meta plus [melody, chords, bass] tracks j =",
"# get midi by index midi = self.midi_files[index] # get midi tracks tracks",
"/ (q_levels / 2) - 1 def q_zero(q_levels): return q_levels // 2 '''",
"return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples",
"time axis, stack on new axis M = np.stack([ np.pad(track, ((0, 0), (0,",
"# return stacked tracks note matrix return M def matrix2melody(self, matrix): ''' extract",
"in range(len(self.file_names)): # import data to memory self.import_data(index) def import_data(self, index): ''' import",
"matrix[:,:,0] # init zero melody, default negative one #melody = np.ones(M.shape[1])*-1 melody =",
") # set melody note at time by index melody[j[1]] = j[0] #",
"__init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len =",
"np.int16) # iterate messages in track for msg in track: # if time",
"import and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for",
"from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files '''",
"str, cache = False, ds: int = 20): ''' init dataset, import midi",
"MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files ''' def __init__(self, dir_path:",
"data dict note = {} # store each note data #note['type'] = msg.type",
"if time step changes, store intermediate notes if int(msg['time']) != 0: # extend",
"midi files ''' # return number of midi files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader):",
"# get max length track s = max([ track.shape[1] for track in m",
"self.midi_files[i] for i in j ] self.file_names = [ self.file_names[i] for i in",
"from mido.MidiFile ''' # initialise tracks list tracks = [] if len(midi.tracks) ==",
") ]).T # append note state vector to track note matrix M =",
"extract melody from note matrix ''' # get track note matrix for melody",
"__getitem__(self, index): ''' return tracks note matrix ''' # check for import state",
"seq_len self.overlap_len = overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples) =",
"note matrix (zero init column) M = np.zeros((128, 1), dtype = np.int16) #",
"import numpy as np # midi file import and parse from mido import",
"= seq_begin + self.seq_len sequences = batch[:, from_index : to_index] input_sequences = sequences[:,",
"over time melody = melody[::self.ds] # store matrix in import list self.import_list[index] =",
"to track note matrix M = np.concatenate( [M, n], axis = 1 )",
"on new axis M = np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1])))",
"MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] # case filter by key if",
"= [] if len(midi.tracks) == 1: ts = [0] else: ts = range(len(midi.tracks))[1:4]",
"[ name for name in os.listdir(dir_path) if 'mid' in name[-4:] ] # import",
"tracks for track in tracks: # initialise note state vector, 7-bit note depth",
"tracks: # initialise note state vector, 7-bit note depth N = np.zeros(128, dtype",
"{} # store each note data #note['type'] = msg.type #note['channel'] = msg.channel note['note']",
"and file name lists self.midi_files = [ self.midi_files[i] for i in j ]",
"files return len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs):",
"time step changes, store intermediate notes if int(msg['time']) != 0: # extend note",
"import torch # array handling import numpy as np # midi file import",
"tracks list tracks = [] if len(midi.tracks) == 1: ts = [0] else:",
"data to memory ''' # get midi by index midi = self.midi_files[index] #",
"# import data to memory self.import_data(index) def import_data(self, index): ''' import midi data",
"return extracted midi tracks return tracks def tracks2matrix(self, tracks: list): ''' convert tracks",
"''' dataset class for midi files ''' def __init__(self, dir_path: str, cache =",
"20): ''' init dataset, import midi files ''' super().__init__() # store downsampling factor",
"ts = [0] else: ts = range(len(midi.tracks))[1:4] # iterate over tracks in midi",
"= int(msg['velocity']) # store track note matrix m.append(M) # get max length track",
"N for _ in range( int(msg['time']) ) ]).T # append note state vector",
"midi files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] #",
": to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous()",
"]).T # append note state vector to track note matrix M = np.concatenate(",
"track for msg in track: # if time step changes, store intermediate notes",
"2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2) -",
"[] # iterate tracks for track in tracks: # initialise note state vector,",
"pre-cache all data if cache: # iterate through midi files for index in",
"= melody def midi2tracks(self, midi): ''' extract tracks from mido.MidiFile ''' # initialise",
"# store downsampling factor self.ds = ds # get and store list midi",
"# tensors and nn modules import torch # array handling import numpy as",
"axis, stack on new axis M = np.stack([ np.pad(track, ((0, 0), (0, s",
"/ 2) - 1 def q_zero(q_levels): return q_levels // 2 ''' def __len__(self):",
"return q_levels // 2 ''' def __len__(self): ''' return total midi files '''",
"tracks from mido.MidiFile ''' # initialise tracks list tracks = [] if len(midi.tracks)",
"iterate tracks for track in tracks: # initialise note state vector, 7-bit note",
"] # init store of import state self.import_list = [ None for _",
"for _ in range(len(self.midi_files)) ] # pre-cache all data if cache: # iterate",
"= self.midi2tracks(midi) # get note tracks matrix matrix = self.tracks2matrix(tracks) # get melody",
"j = [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ]",
"#note['type'] = msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity']",
"get and store list midi files in directory self.file_names = [ name for",
"self.matrix2melody(matrix) # downsample over time melody = melody[::self.ds] # store matrix in import",
"= msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity'] = msg.velocity note['velocity'] =",
"list): ''' convert tracks to matrix ''' # initialise track matricies list m",
"state vector to track note matrix M = np.concatenate( [M, n], axis =",
"return stacked tracks note matrix return M def matrix2melody(self, matrix): ''' extract melody",
"is None: # import data to memory self.import_data(index) # return data if already",
"of import state self.import_list = [ None for _ in range(len(self.midi_files)) ] #",
"i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] # filter midi",
"] # pre-cache all data if cache: # iterate through midi files for",
"dir_path: str, cache = False, ds: int = 20): ''' init dataset, import",
"track notes tracks.append(track) # return extracted midi tracks return tracks def tracks2matrix(self, tracks:",
"= msg.type #note['channel'] = msg.channel note['note'] = msg.note note['time'] = msg.time #note['velocity'] =",
"in ts: # store track data as dict for processing track = []",
"files self.midi_files = [ MidiFile(os.path.join(dir_path, file_name)) for file_name in self.file_names ] # case",
"memory self.import_data(index) def import_data(self, index): ''' import midi data to memory ''' #",
"int(msg['time']) != 0: # extend note state vector over range time step n",
"# return data if already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples",
"= [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 ] #",
"j ] # init store of import state self.import_list = [ None for",
"import os # tensors and nn modules import torch # array handling import",
"to max length of time axis, stack on new axis M = np.stack([",
"stacked tracks note matrix return M def matrix2melody(self, matrix): ''' extract melody from",
"super().__iter__(): (batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin",
"note state vector, 7-bit note depth N = np.zeros(128, dtype = np.int16) #",
"list tracks = [] if len(midi.tracks) == 1: ts = [0] else: ts",
"midi files in directory self.file_names = [ name for name in os.listdir(dir_path) if",
"name for name in os.listdir(dir_path) if 'mid' in name[-4:] ] # import and",
"reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index",
"check for import state if self.import_list[index] is None: # import data to memory",
"np.zeros(128, dtype = np.int16) # initialise track note matrix (zero init column) M",
"linear_quantize(samples, q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *=",
"= sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset,",
"n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index = seq_begin + self.seq_len sequences",
"nn modules import torch # array handling import numpy as np # midi",
"midi files for index in range(len(self.file_names)): # import data to memory self.import_data(index) def",
"max length track s = max([ track.shape[1] for track in m ]) #",
"midi tracks return tracks def tracks2matrix(self, tracks: list): ''' convert tracks to matrix",
"for track in m ], axis = 2) # return stacked tracks note",
"for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ]",
"N = np.zeros(128, dtype = np.int16) # initialise track note matrix (zero init",
"in tracks: # initialise note state vector, 7-bit note depth N = np.zeros(128,",
"[melody, chords, bass] #for i in range(len(midi.tracks))[1:4]: for i in ts: # store",
"np.stack([ np.pad(track, ((0, 0), (0, s - track.shape[1]))) for track in m ],",
"= np.concatenate( [M, n], axis = 1 ) # update value of note",
"# store each note data #note['type'] = msg.type #note['channel'] = msg.channel note['note'] =",
"tracks note matrix return M def matrix2melody(self, matrix): ''' extract melody from note",
"as np # midi file import and parse from mido import MidiFile class",
"index N[int(msg['note'])] = int(msg['velocity']) # store track note matrix m.append(M) # get max",
"range(len(midi.tracks))[1:4]: for i in ts: # store track data as dict for processing",
"get max length track s = max([ track.shape[1] for track in m ])",
"# iterate messages in track for msg in midi.tracks[i][:]: # ensure note data",
"total midi files ''' # return number of midi files return len(self.file_names) class",
"import midi data to memory ''' # get midi by index midi =",
"max([ track.shape[1] for track in m ]) # pad tracks to max length",
"j = [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and",
"file_name)) for file_name in self.file_names ] # case filter by key if False:",
"# update value of note vector by index N[int(msg['note'])] = int(msg['velocity']) # store",
"self.midi_files = [ self.midi_files[i] for i in j ] self.file_names = [ self.file_names[i]",
"= max([ track.shape[1] for track in m ]) # pad tracks to max",
"to memory self.import_data(index) # return data if already imported return self.import_list[index] ''' def",
"+= EPSILON / 2 return samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels",
"''' return tracks note matrix ''' # check for import state if self.import_list[index]",
"in str(self.midi_files[i].tracks[0][2]) ] if False: # get index for only midi with meta",
"# filter midi file and file name lists self.midi_files = [ self.midi_files[i] for",
"files ''' super().__init__() # store downsampling factor self.ds = ds # get and",
"# return extracted midi tracks return tracks def tracks2matrix(self, tracks: list): ''' convert",
"to matrix ''' # initialise track matricies list m = [] # iterate",
"vector over range time step n = np.stack([ N for _ in range(",
"None for _ in range(len(self.midi_files)) ] # pre-cache all data if cache: #",
"batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]:",
"extracted midi tracks return tracks def tracks2matrix(self, tracks: list): ''' convert tracks to",
"only M = matrix[:,:,0] # init zero melody, default negative one #melody =",
"= np.where( M != 0 ) # set melody note at time by",
"index melody[j[1]] = j[0] # return extracted melody return melody def __getitem__(self, index):",
"(batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in",
"= True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index =",
"nonzero j = np.where( M != 0 ) # set melody note at",
"return samples.long() def linear_dequantize(samples, q_levels): return samples.float() / (q_levels / 2) - 1",
"samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples +=",
"matrix2melody(self, matrix): ''' extract melody from note matrix ''' # get track note",
"messages in track for msg in midi.tracks[i][:]: # ensure note data only if",
"track: # if time step changes, store intermediate notes if int(msg['time']) != 0:",
"# pre-cache all data if cache: # iterate through midi files for index",
"init note data dict note = {} # store each note data #note['type']",
"sequences[:, self.overlap_len :].contiguous() yield (input_sequences, reset, target_sequences) reset = False def __len__(self): raise",
"note matrix for melody only M = matrix[:,:,0] # init zero melody, default",
"= batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples,",
"changes, store intermediate notes if int(msg['time']) != 0: # extend note state vector",
"key if False: # get index for only midi with meta plus [melody,",
"import_data(self, index): ''' import midi data to memory ''' # get midi by",
"= overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset",
"samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples",
"get midi by index midi = self.midi_files[index] # get midi tracks tracks =",
"time step n = np.stack([ N for _ in range( int(msg['time']) ) ]).T",
"init dataset, import midi files ''' super().__init__() # store downsampling factor self.ds =",
"store of import state self.import_list = [ None for _ in range(len(self.midi_files)) ]",
"store track data as dict for processing track = [] # iterate messages",
"vector, 7-bit note depth N = np.zeros(128, dtype = np.int16) # initialise track",
"super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self): for",
"= 20): ''' init dataset, import midi files ''' super().__init__() # store downsampling",
"0: # extend note state vector over range time step n = np.stack([",
"in super().__iter__(): (batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len, n_samples, self.seq_len) for",
"**kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def __iter__(self): for batch in super().__iter__():",
"# append note state vector to track note matrix M = np.concatenate( [M,",
"0 if msg.type == 'note_off' else 1 # store note data track.append(note) #",
"= np.stack([ N for _ in range( int(msg['time']) ) ]).T # append note",
"> 3 and \"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get index for",
"# store note data track.append(note) # store track notes tracks.append(track) # return extracted",
"''' init dataset, import midi files ''' super().__init__() # store downsampling factor self.ds",
"get track note matrix for melody only M = matrix[:,:,0] # init zero",
"N[int(msg['note'])] = int(msg['velocity']) # store track note matrix m.append(M) # get max length",
"else: ts = range(len(midi.tracks))[1:4] # iterate over tracks in midi (excl. meta track,",
"1), dtype = np.int16) # iterate messages in track for msg in track:",
"notes tracks.append(track) # return extracted midi tracks return tracks def tracks2matrix(self, tracks: list):",
"# import data to memory self.import_data(index) # return data if already imported return",
"= False, ds: int = 20): ''' init dataset, import midi files '''",
"# midi file import and parse from mido import MidiFile class MelodyDataset(torch.utils.data.Dataset): '''",
"get index (note, time) where nonzero j = np.where( M != 0 )",
"len(midi.tracks) == 1: ts = [0] else: ts = range(len(midi.tracks))[1:4] # iterate over",
"for file_name in self.file_names ] # case filter by key if False: #",
"data if cache: # iterate through midi files for index in range(len(self.file_names)): #",
"for track in m ]) # pad tracks to max length of time",
"in range(len(midi.tracks))[1:4]: for i in ts: # store track data as dict for",
"store track notes tracks.append(track) # return extracted midi tracks return tracks def tracks2matrix(self,",
"at time by index melody[j[1]] = j[0] # return extracted melody return melody",
"len(self.midi_files[i].tracks) > 3 ] # filter midi file and file name lists self.midi_files",
"7-bit note depth N = np.zeros(128, dtype = np.int16) # initialise track note",
"tracks in midi (excl. meta track, extra), [melody, chords, bass] #for i in",
"self.midi_files[index] # get midi tracks tracks = self.midi2tracks(midi) # get note tracks matrix",
"# store matrix in import list self.import_list[index] = melody def midi2tracks(self, midi): '''",
"'note_off' else 1 # store note data track.append(note) # store track notes tracks.append(track)",
"in name[-4:] ] # import and store midi files self.midi_files = [ MidiFile(os.path.join(dir_path,",
"msg in midi.tracks[i][:]: # ensure note data only if msg.type in ['note_on', 'note_off']:",
"def import_data(self, index): ''' import midi data to memory ''' # get midi",
"self.file_names = [ name for name in os.listdir(dir_path) if 'mid' in name[-4:] ]",
"time) where nonzero j = np.where( M != 0 ) # set melody",
"self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len to_index = seq_begin + self.seq_len sequences =",
"range( int(msg['time']) ) ]).T # append note state vector to track note matrix",
"note state vector to track note matrix M = np.concatenate( [M, n], axis",
"self.overlap_len to_index = seq_begin + self.seq_len sequences = batch[:, from_index : to_index] input_sequences",
"# get note tracks matrix matrix = self.tracks2matrix(tracks) # get melody format from",
"store matrix in import list self.import_list[index] = melody def midi2tracks(self, midi): ''' extract",
"[] # iterate messages in track for msg in midi.tracks[i][:]: # ensure note",
"self.overlap_len = overlap_len def __iter__(self): for batch in super().__iter__(): (batch_size, n_samples) = batch.size()",
"batch[:, from_index : to_index] input_sequences = sequences[:, : -1] #print(input_sequences.shape) target_sequences = sequences[:,",
"data if already imported return self.import_list[index] ''' def linear_quantize(samples, q_levels): samples = samples.clone()",
"zero melody, default negative one #melody = np.ones(M.shape[1])*-1 melody = np.zeros(M.shape[1]) # get",
"melody[::self.ds] # store matrix in import list self.import_list[index] = melody def midi2tracks(self, midi):",
"_ in range( int(msg['time']) ) ]).T # append note state vector to track",
"n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin - self.overlap_len",
"*args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs) self.seq_len = seq_len self.overlap_len = overlap_len def",
"3 ] # filter midi file and file name lists self.midi_files = [",
"modules import torch # array handling import numpy as np # midi file",
"tracks return tracks def tracks2matrix(self, tracks: list): ''' convert tracks to matrix '''",
"length track s = max([ track.shape[1] for track in m ]) # pad",
"= [ None for _ in range(len(self.midi_files)) ] # pre-cache all data if",
"dict note = {} # store each note data #note['type'] = msg.type #note['channel']",
"= [] # iterate messages in track for msg in midi.tracks[i][:]: # ensure",
"len(self.file_names) class MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size,",
"if int(msg['time']) != 0: # extend note state vector over range time step",
"track in m ]) # pad tracks to max length of time axis,",
"store each note data #note['type'] = msg.type #note['channel'] = msg.channel note['note'] = msg.note",
"M = np.zeros((128, 1), dtype = np.int16) # iterate messages in track for",
"data to memory self.import_data(index) def import_data(self, index): ''' import midi data to memory",
"import MidiFile class MelodyDataset(torch.utils.data.Dataset): ''' dataset class for midi files ''' def __init__(self,",
"MelodyDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size, seq_len, overlap_len, *args, **kwargs): super().__init__(dataset, batch_size, *args, **kwargs)",
"\"key='{}'\".format(key) in str(self.midi_files[i].tracks[0][2]) ] if False: # get index for only midi with",
"max length of time axis, stack on new axis M = np.stack([ np.pad(track,",
"= [ i for i in range(len(self.file_names)) if len(self.midi_files[i].tracks) > 3 and \"key='{}'\".format(key)",
"q_levels): samples = samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels",
"get midi tracks tracks = self.midi2tracks(midi) # get note tracks matrix matrix =",
"samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON samples += EPSILON / 2 return samples.long()",
"True #print(self.overlap_len, n_samples, self.seq_len) for seq_begin in range(self.overlap_len, n_samples, self.seq_len)[:-1]: from_index = seq_begin",
"__iter__(self): for batch in super().__iter__(): (batch_size, n_samples) = batch.size() reset = True #print(self.overlap_len,",
"midi data to memory ''' # get midi by index midi = self.midi_files[index]",
"= samples.clone() samples -= samples.min(dim=-1)[0].expand_as(samples) samples /= samples.max(dim=-1)[0].expand_as(samples) samples *= q_levels - EPSILON",
"melody only M = matrix[:,:,0] # init zero melody, default negative one #melody"
] |
[
"import * def test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0)",
"os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\",",
"1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert",
"pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for",
"\"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert",
"trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) ==",
"= \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1",
"test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0)",
"assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for f in",
"pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))])",
"for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0)",
"obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) ==",
"pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in",
"not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f",
"assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f",
"os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0)",
"pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj",
"len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0)",
"pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle",
"pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 0",
"== 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0)",
"not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj,",
"save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\",",
"pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f",
"if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\"",
"from cidan.LSSC.functions.pickle_funcs import * def test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir):",
"f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert",
"cidan.LSSC.functions.pickle_funcs import * def test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir)",
"* def test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert",
"trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) assert len([f for f",
"os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert",
"assert not pickle_exist(\"test\", trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for",
"\"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert",
"def test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not",
"in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\", trial_num=0) pickle_clear(trial_num=0) assert not",
"not pickle_exist(\"test\", trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 0 os.rmdir(\"{0}/0/\".format(test_dir)) os.rmdir(test_dir)",
"assert not pickle_exist(\"test\", trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 0 os.rmdir(\"{0}/0/\".format(test_dir))",
"trial_num=0) obj = \"pickle save\" pickle_save(obj, \"test\",trial_num=0) assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))])",
"test_pickle_funcs(): test_dir = \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\",",
"\"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj =",
"= \"test_pickle\" pickle_set_dir(test_dir) if not os.path.isdir(test_dir): os.mkdir(test_dir) pickle_clear(trial_num=0) assert not pickle_exist(\"test\", trial_num=0) obj",
"assert len([f for f in os.listdir(\"{0}/0/\".format(test_dir))]) == 1 assert pickle_load(\"test\", trial_num=0)==obj assert pickle_exist(\"test\","
] |
[
"hgetall(self, key): return await self.execute('hgetall', key) async def scan(self, key): return await self.execute('scan',",
"seconds, value): return await self.execute('setex', key, seconds, value) async def keys(self, key): return",
"options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def init_pool(self, db=None): if",
"self.execute('scan', key) async def connect(loop, db=None): client = AsyncRedisClient(loop) await client.init_pool(db) return client",
"async def get(self, key): return await self.execute('get', key) async def set(self, key, value):",
"_db = options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db",
"Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def get(self, key):",
"async def hgetall(self, key): return await self.execute('hgetall', key) async def scan(self, key): return",
"key) async def set(self, key, value): return await self.execute('set', key, value) async def",
"conn: retsult = await conn.execute(command, *args, **kwargs) return retsult except Exception as e:",
"return await self.execute('keys', key) async def hgetall(self, key): return await self.execute('hgetall', key) async",
"key, seconds, value): return await self.execute('setex', key, seconds, value) async def keys(self, key):",
"def scan(self, key): return await self.execute('scan', key) async def connect(loop, db=None): client =",
"seconds, value) async def keys(self, key): return await self.execute('keys', key) async def hgetall(self,",
"= loop async def init_pool(self, db=None): if db is None: _db = options.redis_db4",
"return await self.execute('get', key) async def set(self, key, value): return await self.execute('set', key,",
"def hgetall(self, key): return await self.execute('hgetall', key) async def scan(self, key): return await",
"*args, **kwargs) return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\",",
"tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def init_pool(self,",
"await self.execute('setex', key, seconds, value) async def keys(self, key): return await self.execute('keys', key)",
"execute error: %s\", e) async def get(self, key): return await self.execute('get', key) async",
"-*- coding:utf-8 -*- import traceback import logging import aioredis from tornado.options import options",
"value): return await self.execute('set', key, value) async def setex(self, key, seconds, value): return",
"await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient,",
"<reponame>fightingfish008/tornado-extensions # -*- coding:utf-8 -*- import traceback import logging import aioredis from tornado.options",
"= 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password, #",
"as conn: retsult = await conn.execute(command, *args, **kwargs) return retsult except Exception as",
"import logging import aioredis from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop",
"self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop,",
"traceback import logging import aioredis from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None):",
"init_pool(self, db=None): if db is None: _db = options.redis_db4 else: _db = db",
"# -*- coding:utf-8 -*- import traceback import logging import aioredis from tornado.options import",
"await self.execute('get', key) async def set(self, key, value): return await self.execute('set', key, value)",
"self.pool.get() as conn: retsult = await conn.execute(command, *args, **kwargs) return retsult except Exception",
"loop async def init_pool(self, db=None): if db is None: _db = options.redis_db4 else:",
"key, seconds, value) async def keys(self, key): return await self.execute('keys', key) async def",
"self.execute('keys', key) async def hgetall(self, key): return await self.execute('hgetall', key) async def scan(self,",
"logging import aioredis from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop =",
"return await self.execute('setex', key, seconds, value) async def keys(self, key): return await self.execute('keys',",
"retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def",
"await conn.execute(command, *args, **kwargs) return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute",
"value): return await self.execute('setex', key, seconds, value) async def keys(self, key): return await",
"key): return await self.execute('scan', key) async def connect(loop, db=None): client = AsyncRedisClient(loop) await",
"def setex(self, key, seconds, value): return await self.execute('setex', key, seconds, value) async def",
"import traceback import logging import aioredis from tornado.options import options class AsyncRedisClient(object): def",
"from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def",
"_db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop",
"return await self.execute('hgetall', key) async def scan(self, key): return await self.execute('scan', key) async",
"**kwargs) return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e)",
"self).__init__() async def execute(self, command, *args, **kwargs): try: async with self.pool.get() as conn:",
"e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def get(self, key): return await",
"encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command,",
"key): return await self.execute('get', key) async def set(self, key, value): return await self.execute('set',",
"-*- import traceback import logging import aioredis from tornado.options import options class AsyncRedisClient(object):",
"self.execute('get', key) async def set(self, key, value): return await self.execute('set', key, value) async",
"async def set(self, key, value): return await self.execute('set', key, value) async def setex(self,",
"key) async def scan(self, key): return await self.execute('scan', key) async def connect(loop, db=None):",
"await self.execute('scan', key) async def connect(loop, db=None): client = AsyncRedisClient(loop) await client.init_pool(db) return",
"minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command, *args,",
"def keys(self, key): return await self.execute('keys', key) async def hgetall(self, key): return await",
"= self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs): try: async",
"return await self.execute('set', key, value) async def setex(self, key, seconds, value): return await",
"_db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await",
"logging.error(\"redis execute error: %s\", e) async def get(self, key): return await self.execute('get', key)",
"def get(self, key): return await self.execute('get', key) async def set(self, key, value): return",
"self.execute('setex', key, seconds, value) async def keys(self, key): return await self.execute('keys', key) async",
"uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password,",
"async with self.pool.get() as conn: retsult = await conn.execute(command, *args, **kwargs) return retsult",
"options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5,",
"key) async def hgetall(self, key): return await self.execute('hgetall', key) async def scan(self, key):",
"self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs): try: async with",
"async def setex(self, key, seconds, value): return await self.execute('setex', key, seconds, value) async",
"db is None: _db = options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format(",
"options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool",
"= options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db )",
"setex(self, key, seconds, value): return await self.execute('setex', key, seconds, value) async def keys(self,",
"coding:utf-8 -*- import traceback import logging import aioredis from tornado.options import options class",
"set(self, key, value): return await self.execute('set', key, value) async def setex(self, key, seconds,",
"def execute(self, command, *args, **kwargs): try: async with self.pool.get() as conn: retsult =",
"def init_pool(self, db=None): if db is None: _db = options.redis_db4 else: _db =",
"super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs): try: async with self.pool.get() as",
"logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def get(self, key): return await self.execute('get',",
"password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def",
"*args, **kwargs): try: async with self.pool.get() as conn: retsult = await conn.execute(command, *args,",
"def __init__(self,loop=None): self.loop = loop async def init_pool(self, db=None): if db is None:",
"db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool( uri,",
"uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async",
"None: _db = options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port,",
"key): return await self.execute('hgetall', key) async def scan(self, key): return await self.execute('scan', key)",
"self.execute('set', key, value) async def setex(self, key, seconds, value): return await self.execute('setex', key,",
"execute(self, command, *args, **kwargs): try: async with self.pool.get() as conn: retsult = await",
"aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__()",
"AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def init_pool(self, db=None): if db is",
"except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def get(self,",
"get(self, key): return await self.execute('get', key) async def set(self, key, value): return await",
"conn.execute(command, *args, **kwargs) return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error:",
"error: %s\", e) async def get(self, key): return await self.execute('get', key) async def",
"await self.execute('keys', key) async def hgetall(self, key): return await self.execute('hgetall', key) async def",
"options.redis_port, _db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10,",
"value) async def setex(self, key, seconds, value): return await self.execute('setex', key, seconds, value)",
"= await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, )",
"= await conn.execute(command, *args, **kwargs) return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis",
"async def init_pool(self, db=None): if db is None: _db = options.redis_db4 else: _db",
"if db is None: _db = options.redis_db4 else: _db = db uri =",
"command, *args, **kwargs): try: async with self.pool.get() as conn: retsult = await conn.execute(command,",
"value) async def keys(self, key): return await self.execute('keys', key) async def hgetall(self, key):",
") self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\", minsize=5, maxsize=10, loop =",
") super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs): try: async with self.pool.get()",
"try: async with self.pool.get() as conn: retsult = await conn.execute(command, *args, **kwargs) return",
"return retsult except Exception as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async",
"import aioredis from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop",
"import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def init_pool(self, db=None):",
"keys(self, key): return await self.execute('keys', key) async def hgetall(self, key): return await self.execute('hgetall',",
"with self.pool.get() as conn: retsult = await conn.execute(command, *args, **kwargs) return retsult except",
"retsult = await conn.execute(command, *args, **kwargs) return retsult except Exception as e: logging.error(traceback.print_exc())",
"key, value): return await self.execute('set', key, value) async def setex(self, key, seconds, value):",
"scan(self, key): return await self.execute('scan', key) async def connect(loop, db=None): client = AsyncRedisClient(loop)",
"return await self.execute('scan', key) async def connect(loop, db=None): client = AsyncRedisClient(loop) await client.init_pool(db)",
"key, value) async def setex(self, key, seconds, value): return await self.execute('setex', key, seconds,",
"loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs): try:",
"as e: logging.error(traceback.print_exc()) logging.error(\"redis execute error: %s\", e) async def get(self, key): return",
"else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool =",
"is None: _db = options.redis_db4 else: _db = db uri = 'redis://{}:{}/{}'.format( options.redis_host,",
"maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self, command, *args, **kwargs):",
"async def keys(self, key): return await self.execute('keys', key) async def hgetall(self, key): return",
"db=None): if db is None: _db = options.redis_db4 else: _db = db uri",
"async def execute(self, command, *args, **kwargs): try: async with self.pool.get() as conn: retsult",
"'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool( uri, password=options.redis_password, # encoding=\"utf-8\",",
"e) async def get(self, key): return await self.execute('get', key) async def set(self, key,",
"= db uri = 'redis://{}:{}/{}'.format( options.redis_host, options.redis_port, _db ) self.pool = await aioredis.create_pool(",
"async def scan(self, key): return await self.execute('scan', key) async def connect(loop, db=None): client",
"class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async def init_pool(self, db=None): if db",
"__init__(self,loop=None): self.loop = loop async def init_pool(self, db=None): if db is None: _db",
"self.execute('hgetall', key) async def scan(self, key): return await self.execute('scan', key) async def connect(loop,",
"**kwargs): try: async with self.pool.get() as conn: retsult = await conn.execute(command, *args, **kwargs)",
"key): return await self.execute('keys', key) async def hgetall(self, key): return await self.execute('hgetall', key)",
"await self.execute('hgetall', key) async def scan(self, key): return await self.execute('scan', key) async def",
"aioredis from tornado.options import options class AsyncRedisClient(object): def __init__(self,loop=None): self.loop = loop async",
"self.loop = loop async def init_pool(self, db=None): if db is None: _db =",
"%s\", e) async def get(self, key): return await self.execute('get', key) async def set(self,",
"def set(self, key, value): return await self.execute('set', key, value) async def setex(self, key,",
"# encoding=\"utf-8\", minsize=5, maxsize=10, loop = self.loop, ) super(AsyncRedisClient, self).__init__() async def execute(self,",
"await self.execute('set', key, value) async def setex(self, key, seconds, value): return await self.execute('setex',"
] |
[
"from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class",
"self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def GeckoCodeCreate(self): self.clicked = True self.close()",
"self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close)",
"Qt from PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False):",
"else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def GeckoCodeCreate(self):",
"PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False)",
"False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def GeckoCodeCreate(self): self.clicked = True",
"from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode):",
"QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not",
"self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec()",
"__init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False",
"if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate)",
"ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked",
"self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message)",
"import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message)",
"self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def",
"from PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent)",
"def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked =",
"import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self)",
"Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close)",
"self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def GeckoCodeCreate(self): self.clicked",
"geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1)",
"= False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show() self.exec() def GeckoCodeCreate(self): self.clicked =",
"super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error)",
"errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error)",
"self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else: self.clicked = False self.ErrorTitle_GC.setText(error) self.ErrorMessage_GC.setText(message) self.ErrorClose_GC.clicked.connect(self.close) self.ErrorCreate_GC.clicked.connect(self.GeckoCodeCreate) self.MainWidget.setCurrentIndex(1) self.show()",
"PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error):",
"import Qt from PyQt5.QtWidgets import QDialog from errorhandler_ui import Ui_Error class ShowError(QDialog,Ui_Error): def",
"class ShowError(QDialog,Ui_Error): def __init__(self,error,message,parent=None,geckocode=False): super().__init__(parent) self.setWindowFlag(Qt.WindowContextHelpButtonHint,False) self.setupUi(self) if(not geckocode): self.ErrorTitle.setText(error) self.ErrorMessage.setText(message) self.ErrorClose.clicked.connect(self.close) else:"
] |
[
"self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index',",
"## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ##",
"self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints():",
"pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod",
">= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return",
"self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode",
"def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData())",
"import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import",
"or agreed to in writing, software ## distributed under the License is distributed",
"is distributed on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF",
"FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single)",
"PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes",
"NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return",
"return 'For loop begin block' def reset(self): self.currentIndex = 0 self.prevIndex = -1",
"onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex =",
"'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody =",
"<NAME>, <NAME> ## Licensed under the Apache License, Version 2.0 (the \"License\"); ##",
"= -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex",
"= False self.currentIndex = 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None,",
"self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental()",
"None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired",
"the Apache License, Version 2.0 (the \"License\"); ## you may not use this",
"return ['iter'] @staticmethod def description(): return 'For loop begin block' def reset(self): self.currentIndex",
"not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start() self._working = True #self.onNext(*args, **kwargs)",
"## limitations under the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry",
"loop begin block' def reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working =",
"'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode =",
"PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading",
"CONDITIONS OF ANY KIND, either express or implied. ## See the License for",
"import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name):",
"PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working",
"self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block',",
"self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod",
"category(): return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def description(): return 'For",
"self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return False def",
"**kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call()",
"agreed to in writing, software ## distributed under the License is distributed on",
"under the License is distributed on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES",
"not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph() is not",
"helper @staticmethod def category(): return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def",
"the License is distributed on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR",
"at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed to in",
"for the specific language governing permissions and ## limitations under the License. from",
"self.prevIndex = -1 #self._working = False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex",
"= PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return False def onNext(self, *args,",
"if self.graph() is not loopEndNode.graph(): err = \"block ends in different graphs\" self.setError(err)",
"False def onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex)",
"self.currentIndex = 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex",
"['iter'] @staticmethod def description(): return 'For loop begin block' def reset(self): self.currentIndex =",
"indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working",
"return True return False def onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex",
"Apache License, Version 2.0 (the \"License\"); ## you may not use this file",
"self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path():",
"import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class",
"self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin')",
"PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common",
"copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law",
"or implied. ## See the License for the specific language governing permissions and",
"from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name)",
"= self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working =",
"limitations under the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from",
"if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if",
"= self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() !=",
"compliance with the License. ## You may obtain a copy of the License",
"PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return False def onNext(self, *args, **kwargs):",
"helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl' @staticmethod",
"IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"= self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\")",
"self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin')",
"= 0 self.prevIndex = -1 #self._working = False def isDone(self): indexTo = self.lastIndex.getData()",
"the specific language governing permissions and ## limitations under the License. from PyFlow.Core",
"loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph(): err =",
"software ## distributed under the License is distributed on an \"AS IS\" BASIS,",
"isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call()",
"specific language governing permissions and ## limitations under the License. from PyFlow.Core import",
"language governing permissions and ## limitations under the License. from PyFlow.Core import NodeBase",
"helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl' @staticmethod def keywords(): return ['iter']",
"* from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin,",
"under the Apache License, Version 2.0 (the \"License\"); ## you may not use",
"if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph(): err",
"loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args,",
"'For loop begin block' def reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working",
"self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single)",
"self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph(): err = \"block ends in",
"keywords(): return ['iter'] @staticmethod def description(): return 'For loop begin block' def reset(self):",
"threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex =",
"## Licensed under the Apache License, Version 2.0 (the \"License\"); ## you may",
"= -1 #self._working = False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >=",
"@staticmethod def description(): return 'For loop begin block' def reset(self): self.currentIndex = 0",
"def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex =",
"use this file except in compliance with the License. ## You may obtain",
"self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath)",
"#loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return False def onNext(self,",
"import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex",
"file except in compliance with the License. ## You may obtain a copy",
"self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args,",
"not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start() self._working =",
"## Unless required by applicable law or agreed to in writing, software ##",
"## Copyright 2015-2019 <NAME>, <NAME> ## Licensed under the Apache License, Version 2.0",
"self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if",
"(the \"License\"); ## you may not use this file except in compliance with",
"def onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex",
"0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start',",
"None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph():",
"= False return True return False def onNext(self, *args, **kwargs): while not self.isDone():",
"Copyright 2015-2019 <NAME>, <NAME> ## Licensed under the Apache License, Version 2.0 (the",
"See the License for the specific language governing permissions and ## limitations under",
"= self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper()",
"self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if",
"not loopEndNode.graph(): err = \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else:",
"express or implied. ## See the License for the specific language governing permissions",
"compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is",
"http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed to in writing, software",
"obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by",
"= 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex =",
"helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl' @staticmethod def",
"#self._working = False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset()",
"applicable law or agreed to in writing, software ## distributed under the License",
"name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex = -1 self.inExec",
"'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper",
"self._working = False return True return False def onNext(self, *args, **kwargs): while not",
"PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return",
"is not loopEndNode.graph(): err = \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return",
"from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from",
"## you may not use this file except in compliance with the License.",
"<NAME> ## Licensed under the Apache License, Version 2.0 (the \"License\"); ## you",
"OF ANY KIND, either express or implied. ## See the License for the",
"loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph()",
"you may not use this file except in compliance with the License. ##",
"self._working = False self.currentIndex = 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin',",
"graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread =",
"from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import",
"2.0 (the \"License\"); ## you may not use this file except in compliance",
"return False def onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex:",
"err = \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not",
"ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not",
"self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor",
"KIND, either express or implied. ## See the License for the specific language",
"from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from",
"@staticmethod def category(): return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def description():",
"False return True return False def onNext(self, *args, **kwargs): while not self.isDone(): if",
"return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs))",
"distributed on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"-1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex =",
"= self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin')",
"'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin')",
"in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working:",
"Unless required by applicable law or agreed to in writing, software ## distributed",
"block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor =",
"self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode",
"block' def reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working = False def",
"forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex",
"0 self.prevIndex = -1 #self._working = False def isDone(self): indexTo = self.lastIndex.getData() if",
"pair\") return if self.graph() is not loopEndNode.graph(): err = \"block ends in different",
"reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working = False def isDone(self): indexTo",
"to in writing, software ## distributed under the License is distributed on an",
"\"License\"); ## you may not use this file except in compliance with the",
"License. ## You may obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0",
"implied. ## See the License for the specific language governing permissions and ##",
"OR CONDITIONS OF ANY KIND, either express or implied. ## See the License",
"if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return",
"License is distributed on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS",
"self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop',",
"def category(): return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def description(): return",
"self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True",
"#loopEndNode.completed.call() self._working = False return True return False def onNext(self, *args, **kwargs): while",
"License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed to",
"PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE",
"@staticmethod def keywords(): return ['iter'] @staticmethod def description(): return 'For loop begin block'",
"writing, software ## distributed under the License is distributed on an \"AS IS\"",
"loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid",
"self.path(): self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph(): err = \"block ends",
"*args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not",
"is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\") return if self.graph() is",
"= self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode =",
"License, Version 2.0 (the \"License\"); ## you may not use this file except",
"except in compliance with the License. ## You may obtain a copy of",
"'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def description(): return 'For loop begin",
"Licensed under the Apache License, Version 2.0 (the \"License\"); ## you may not",
"= \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath))",
"permissions and ## limitations under the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry",
"def reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working = False def isDone(self):",
"begin block' def reset(self): self.currentIndex = 0 self.prevIndex = -1 #self._working = False",
"## See the License for the specific language governing permissions and ## limitations",
"may obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required",
"return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod def description(): return 'For loop",
"class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0",
"= NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category():",
"governing permissions and ## limitations under the License. from PyFlow.Core import NodeBase from",
"of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or",
"this file except in compliance with the License. ## You may obtain a",
"from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def",
"with the License. ## You may obtain a copy of the License at",
"= self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin')",
"'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index =",
"-1 #self._working = False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo:",
"'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE",
"self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False",
"return if self.graph() is not loopEndNode.graph(): err = \"block ends in different graphs\"",
"not use this file except in compliance with the License. ## You may",
"BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"@staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return",
"= self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin')",
"import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working =",
"self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody', 'ExecPin') self.index",
"\"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if",
"__init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex = -1",
"FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self, name): super(forLoopBegin, self).__init__(name) self._working = False",
"## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed to in writing,",
"the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed",
"Version 2.0 (the \"License\"); ## you may not use this file except in",
"True return False def onNext(self, *args, **kwargs): while not self.isDone(): if self.currentIndex >",
"import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import",
"else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start()",
"distributed under the License is distributed on an \"AS IS\" BASIS, ## WITHOUT",
"ANY KIND, either express or implied. ## See the License for the specific",
"License for the specific language governing permissions and ## limitations under the License.",
"the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import",
"def keywords(): return ['iter'] @staticmethod def description(): return 'For loop begin block' def",
"!= self.path(): self.setError(\"Invalid pair\") return if self.graph() is not loopEndNode.graph(): err = \"block",
"self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper =",
"License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper",
"and ## limitations under the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import",
"= self.createOutputPin('LoopBody', 'ExecPin') self.index = self.createOutputPin('Index', 'IntPin') self.headerColor = FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def",
"NodePinsSuggestionsHelper from PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase):",
"self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody = self.createOutputPin('LoopBody',",
"helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def",
"on an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"= False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode",
"under the License. from PyFlow.Core import NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase",
"helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl'",
"the License for the specific language governing permissions and ## limitations under the",
"helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl' @staticmethod def keywords(): return",
"required by applicable law or agreed to in writing, software ## distributed under",
"an \"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"self.graph() is not loopEndNode.graph(): err = \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err)",
"while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def",
"self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start() self._working",
"self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin') self.loopEndNode.setInputWidgetVariant(\"ObjectPathWIdget\") self.loopBody",
"self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset()",
"different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread",
"= PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData() != self.path(): self.setError(\"Invalid pair\")",
"the License. ## You may obtain a copy of the License at ##",
"self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec',",
"law or agreed to in writing, software ## distributed under the License is",
"helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper @staticmethod def category(): return 'FlowControl' @staticmethod def keywords():",
"in compliance with the License. ## You may obtain a copy of the",
"may not use this file except in compliance with the License. ## You",
"= FLOW_CONTROL_ORANGE self.setExperimental() @staticmethod def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin')",
"\"AS IS\" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"return helper @staticmethod def category(): return 'FlowControl' @staticmethod def keywords(): return ['iter'] @staticmethod",
"by applicable law or agreed to in writing, software ## distributed under the",
"self.currentIndex = 0 self.prevIndex = -1 #self._working = False def isDone(self): indexTo =",
"> self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath",
"def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode",
"False def isDone(self): indexTo = self.lastIndex.getData() if self.currentIndex >= indexTo: self.reset() #loopEndNode =",
"in writing, software ## distributed under the License is distributed on an \"AS",
"description(): return 'For loop begin block' def reset(self): self.currentIndex = 0 self.prevIndex =",
"self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute) self.firstIndex = self.createInputPin('Start', 'IntPin')",
"You may obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless",
"def description(): return 'For loop begin block' def reset(self): self.currentIndex = 0 self.prevIndex",
"self.firstIndex = self.createInputPin('Start', 'IntPin') self.lastIndex = self.createInputPin('Stop', 'IntPin') self.loopEndNode = self.createInputPin('Paired block', 'StringPin')",
"self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath = self.loopEndNode.getData()",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the",
"not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self,",
"False self.currentIndex = 0 self.prevIndex = -1 self.inExec = self.createInputPin('inExec', 'ExecPin', None, self.compute)",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See",
"*args, **kwargs): while not self.isDone(): if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex",
"indexTo: self.reset() #loopEndNode = PathsRegistry().getEntity(self.loopEndNode.getData()) #loopEndNode.completed.call() self._working = False return True return False",
"if self.currentIndex > self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs):",
"**kwargs): self.reset() endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None:",
"## distributed under the License is distributed on an \"AS IS\" BASIS, ##",
"either express or implied. ## See the License for the specific language governing",
"self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{} not found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self,",
"if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start() self._working = True #self.onNext(*args,",
"self.prevIndex: self.index.setData(self.currentIndex) self.prevIndex = self.currentIndex self.loopBody.call() def compute(self, *args, **kwargs): self.reset() endNodePath =",
"def pinTypeHints(): helper = NodePinsSuggestionsHelper() helper.addInputDataType('ExecPin') helper.addInputDataType('IntPin') helper.addOutputDataType('ExecPin') helper.addOutputDataType('IntPin') helper.addInputStruct(StructureType.Single) helper.addOutputStruct(StructureType.Single) return helper",
"PyFlow.Core.Common import * from PyFlow.Packages.PyFlowBase.Nodes import FLOW_CONTROL_ORANGE import threading class forLoopBegin(NodeBase): def __init__(self,",
"endNodePath = self.loopEndNode.getData() loopEndNode = PathsRegistry().getEntity(endNodePath) if loopEndNode is not None: if loopEndNode.loopBeginNode.getData()",
"2015-2019 <NAME>, <NAME> ## Licensed under the Apache License, Version 2.0 (the \"License\");",
"found\".format(endNodePath)) if not self._working: self.thread = threading.Thread(target=self.onNext,args=(self, args, kwargs)) self.thread.start() self._working = True",
"## You may obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ##",
"loopEndNode.graph(): err = \"block ends in different graphs\" self.setError(err) loopEndNode.setError(err) return else: self.setError(\"{}",
"super(forLoopBegin, self).__init__(name) self._working = False self.currentIndex = 0 self.prevIndex = -1 self.inExec =",
"a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable",
"NodeBase from PyFlow.Core.PathsRegistry import PathsRegistry from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper from PyFlow.Core.Common import *"
] |
[
"= re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd, jmp_addr,",
"cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name == \"tpl\":",
"1 else 1 else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr",
"\"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif",
"= re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for cmd",
"= re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands if __name__ ==",
"elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else 1",
"== \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else: raise",
"cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line:",
"line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for cmd in [\"jie\", \"jio\"]]):",
"//= 2 self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr",
"re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd, jmp_addr, _",
"= jump_addr class Program: def __init__(self, commands, registers): self.commands = commands self.registers =",
"commands = [] for line in f.readlines(): if any([cmd in line for cmd",
"self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1",
"command: \", cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm",
"return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f: commands = [] for",
"+= 1 self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif",
"register, jump_addr=None): self.name = name self.register = register self.jump_addr = jump_addr class Program:",
"any([cmd in line for cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _",
"solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name):",
"cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return",
"def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def",
"self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"]",
"1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr",
"re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for cmd in",
"re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands if __name__ == '__main__':",
"def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr",
"raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def",
"= [] for line in f.readlines(): if any([cmd in line for cmd in",
"def parse(file_name): with open(file_name, \"r\") as f: commands = [] for line in",
"while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\":",
"line for cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+)",
"self.register = register self.jump_addr = jump_addr class Program: def __init__(self, commands, registers): self.commands",
"in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line)",
"< len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run()",
"\"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register] +=",
"def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\":",
"\"jmp\" in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None,",
"_ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for",
"+= cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported command: \",",
"self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3",
"cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported command: \", cmd.name)",
"len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return",
"+= cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2",
"None, int(jmp_addr))) if any([cmd in line for cmd in [\"jie\", \"jio\"]]): _, cmd,",
"def __init__(self, name, register, jump_addr=None): self.name = name self.register = register self.jump_addr =",
"_ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands if __name__",
"self.name = name self.register = register self.jump_addr = jump_addr class Program: def __init__(self,",
"+= 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif",
"== \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register]",
"cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in",
"if any([cmd in line for cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr,",
"\"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported",
"elif \"jmp\" in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd,",
"1 self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name",
"= self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif",
"1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name",
"cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name == \"inc\":",
"cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else 1 elif cmd.name == \"jio\":",
"for line in f.readlines(): if any([cmd in line for cmd in [\"inc\", \"tpl\",",
"([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands if __name__ == '__main__': print(solve(parse(\"data.txt\")))",
"cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name == \"jmp\":",
"any([cmd in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _",
"pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f: commands = [] for line",
"\"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\"",
"r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands",
"name self.register = register self.jump_addr = jump_addr class Program: def __init__(self, commands, registers):",
"ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands):",
"line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if",
"registers self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\":",
"{\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as",
"if self.registers[cmd.register] % 2 == 0 else 1 elif cmd.name == \"jio\": self.instr_ptr",
"elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr +=",
"for cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]),",
"== \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr",
"= name self.register = register self.jump_addr = jump_addr class Program: def __init__(self, commands,",
"self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0, \"b\": 0})",
"== \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register]",
"f: commands = [] for line in f.readlines(): if any([cmd in line for",
"[] for line in f.readlines(): if any([cmd in line for cmd in [\"inc\",",
"in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd,",
"class Program: def __init__(self, commands, registers): self.commands = commands self.registers = registers self.instr_ptr",
"_, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd",
"= 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //=",
"parse(file_name): with open(file_name, \"r\") as f: commands = [] for line in f.readlines():",
"Command: def __init__(self, name, register, jump_addr=None): self.name = name self.register = register self.jump_addr",
"commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\",",
"= registers self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name ==",
"cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1",
"pgm = Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with",
"0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f:",
"\"r\") as f: commands = [] for line in f.readlines(): if any([cmd in",
"self.jump_addr = jump_addr class Program: def __init__(self, commands, registers): self.commands = commands self.registers",
"= commands self.registers = registers self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr]",
"re class Command: def __init__(self, name, register, jump_addr=None): self.name = name self.register =",
"cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands,",
"line in f.readlines(): if any([cmd in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]):",
"0 else 1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] ==",
"\"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else 1 elif",
"else 1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1",
"registers): self.commands = commands self.registers = registers self.instr_ptr = 0 def exec_next_command(self): cmd",
"*= 3 self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr",
"self.registers[cmd.register] % 2 == 0 else 1 elif cmd.name == \"jio\": self.instr_ptr +=",
"([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd, jmp_addr, _ =",
"else 1 else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr <",
"in f.readlines(): if any([cmd in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _,",
"== 0 else 1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register]",
"([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for cmd in [\"jie\",",
"3 self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr +=",
"2 == 0 else 1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if",
"cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line)",
"jump_addr=None): self.name = name self.register = register self.jump_addr = jump_addr class Program: def",
"\"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f: commands",
"exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr +=",
"\"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r,",
"\"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr +=",
"jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr))) return commands if",
"self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name ==",
"self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported command:",
"with open(file_name, \"r\") as f: commands = [] for line in f.readlines(): if",
"int(jmp_addr))) if any([cmd in line for cmd in [\"jie\", \"jio\"]]): _, cmd, r,",
"if self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported command: \", cmd.name) def",
"self.instr_ptr += 1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1",
"__init__(self, commands, registers): self.commands = commands self.registers = registers self.instr_ptr = 0 def",
"jump_addr class Program: def __init__(self, commands, registers): self.commands = commands self.registers = registers",
"= register self.jump_addr = jump_addr class Program: def __init__(self, commands, registers): self.commands =",
"_, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in",
"register self.jump_addr = jump_addr class Program: def __init__(self, commands, registers): self.commands = commands",
"% 2 == 0 else 1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr",
"r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _,",
"commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line for cmd in [\"jie\", \"jio\"]]): _,",
"pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f: commands = []",
"Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\")",
"_ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd,",
"\"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *=",
"1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name",
"in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ =",
"self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] %",
"elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name ==",
"self.registers = registers self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name",
"class Command: def __init__(self, name, register, jump_addr=None): self.name = name self.register = register",
"[\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\", line) commands.append(Command(cmd, r))",
"1 elif cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else",
"\"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register]",
"[\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd,",
"__init__(self, name, register, jump_addr=None): self.name = name self.register = register self.jump_addr = jump_addr",
"self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else 1 elif cmd.name",
"r)) elif \"jmp\" in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line)",
"import re class Command: def __init__(self, name, register, jump_addr=None): self.name = name self.register",
"self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1",
"cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 ==",
"self.commands = commands self.registers = registers self.instr_ptr = 0 def exec_next_command(self): cmd =",
"as f: commands = [] for line in f.readlines(): if any([cmd in line",
"0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2",
"if any([cmd in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r,",
"name, register, jump_addr=None): self.name = name self.register = register self.jump_addr = jump_addr class",
"2 self.instr_ptr += 1 elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr +=",
"cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr",
"commands self.registers = registers self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if",
"+= 1 elif cmd.name == \"inc\": self.registers[cmd.register] += 1 self.instr_ptr += 1 elif",
"cmd.name == \"jio\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] == 1 else 1 else:",
"in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr)))",
"line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+)",
"== 1 else 1 else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while",
"1 else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr < len(self.commands):",
"== \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else 1",
"line) commands.append(Command(cmd, r)) elif \"jmp\" in line: _, cmd, jmp_addr, _ = re.split(r\"([a-z]+)",
"= Program(commands, {\"a\": 0, \"b\": 0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name,",
"== \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if",
"elif cmd.name == \"tpl\": self.registers[cmd.register] *= 3 self.instr_ptr += 1 elif cmd.name ==",
"self.instr_ptr = 0 def exec_next_command(self): cmd = self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register]",
"+= cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else 1 elif cmd.name ==",
"run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm = Program(commands, {\"a\": 0,",
"\", cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command() def solve(commands): pgm =",
"for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd, r, _ = re.split(r\"([a-z]+) ([a|b])\",",
"_, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\", line) commands.append(Command(cmd, r, int(jmp_addr)))",
"commands, registers): self.commands = commands self.registers = registers self.instr_ptr = 0 def exec_next_command(self):",
"elif cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 == 0",
"cmd.name == \"jie\": self.instr_ptr += cmd.jump_addr if self.registers[cmd.register] % 2 == 0 else",
"jmp_addr, _ = re.split(r\"([a-z]+) ([+|-][0-9]+)\", line) commands.append(Command(cmd, None, int(jmp_addr))) if any([cmd in line",
"0}) pgm.run() return pgm.registers[\"b\"] def parse(file_name): with open(file_name, \"r\") as f: commands =",
"else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self): while self.instr_ptr < len(self.commands): self.exec_next_command()",
"self.registers[cmd.register] == 1 else 1 else: raise ValueError(\"Unsupported command: \", cmd.name) def run(self):",
"def __init__(self, commands, registers): self.commands = commands self.registers = registers self.instr_ptr = 0",
"+= 1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr elif cmd.name == \"jie\":",
"cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ = re.split(r\"([a-z]+) ([a|b]), ([+\\-0-9]+)\",",
"self.commands[self.instr_ptr] if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name",
"open(file_name, \"r\") as f: commands = [] for line in f.readlines(): if any([cmd",
"f.readlines(): if any([cmd in line for cmd in [\"inc\", \"tpl\", \"hlf\"]]): _, cmd,",
"self.registers[cmd.register] += 1 self.instr_ptr += 1 elif cmd.name == \"jmp\": self.instr_ptr += cmd.jump_addr",
"Program: def __init__(self, commands, registers): self.commands = commands self.registers = registers self.instr_ptr =",
"in line for cmd in [\"jie\", \"jio\"]]): _, cmd, r, jmp_addr, _ =",
"if cmd.name == \"hlf\": self.registers[cmd.register] //= 2 self.instr_ptr += 1 elif cmd.name =="
] |
[
"\"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"),",
"\"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField(",
"\"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True,",
"migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations = [",
"3.0.5 on 2020-04-17 21:07 import uuid import django_fsm from django.db import migrations, models",
"operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField(",
"name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[",
"protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"),",
"[ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\",",
"migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs",
"verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\",",
"2020-04-17 21:07 import uuid import django_fsm from django.db import migrations, models class Migration(migrations.Migration):",
"name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process",
"), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\",",
"model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"),",
"manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[",
"dependencies = [ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\",",
"), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\",",
"name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"),",
"migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\",",
"(\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ],",
"import migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations =",
"field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"),",
"class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",),",
"field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ],",
"] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ),",
"default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\",",
"uuid import django_fsm from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\",",
"(\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\",",
"\"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"),",
"(\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField(",
"name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\",",
"max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in",
"import django_fsm from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\",",
"# Generated by Django 3.0.5 on 2020-04-17 21:07 import uuid import django_fsm from",
"= [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\",",
"), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"),",
"(\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4,",
"], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"),",
"import uuid import django_fsm from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\",",
"\"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\",",
"= [ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\",",
"\"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"),",
"django_fsm from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"),",
"migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\",",
"(\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially",
"migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField(",
"models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\",",
"by Django 3.0.5 on 2020-04-17 21:07 import uuid import django_fsm from django.db import",
"model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge",
"21:07 import uuid import django_fsm from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"Generated by Django 3.0.5 on 2020-04-17 21:07 import uuid import django_fsm from django.db",
"paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\", max_length=50,",
"field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"),",
"(\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50,",
"(\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund",
"default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\", name=\"payment_status\", field=django_fsm.FSMField( choices=[ (\"new\", \"new\"), (\"prepared\",",
"(\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\", max_length=50, protected=True,",
"model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual",
"\"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\",",
"\"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ]",
"on 2020-04-17 21:07 import uuid import django_fsm from django.db import migrations, models class",
"(\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\", max_length=50, protected=True, ), ),",
"\"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True, default=uuid.uuid4, max_length=100),",
"\"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\", max_length=50, protected=True, ),",
"\"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ), ), migrations.AddField( model_name=\"paymententry\",",
"\"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"), ], default=\"prepared\", max_length=50, protected=True, ), ), ]",
"choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\",",
"(\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"), (\"check\", \"needs manual verification\"), ], default=\"unknown\", max_length=50, protected=True, ),",
"process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\",",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations",
"Django 3.0.5 on 2020-04-17 21:07 import uuid import django_fsm from django.db import migrations,",
"[ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField( model_name=\"paymententry\", name=\"ext_id\", field=models.CharField(db_index=True,",
"(\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"),",
"started\"), (\"partially_paid\", \"partially paid\"), (\"paid\", \"paid\"), (\"failed\", \"failed\"), (\"refund_started\", \"refund started\"), (\"refunded\", \"refunded\"),",
"max_length=100), ), migrations.AddField( model_name=\"paymententry\", name=\"fraud_status\", field=django_fsm.FSMField( choices=[ (\"unknown\", \"unknown\"), (\"accepted\", \"accepted\"), (\"rejected\", \"rejected\"),",
"(\"prepared\", \"in progress\"), (\"pre-auth\", \"pre-authed\"), (\"charge_started\", \"charge process started\"), (\"partially_paid\", \"partially paid\"), (\"paid\",",
"Migration(migrations.Migration): dependencies = [ (\"paywall\", \"0001_initial\"), ] operations = [ migrations.RemoveField(model_name=\"paymententry\", name=\"payment\",), migrations.AddField("
] |
[
"data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance",
"to for # prediction perfomance analysis. Could be the test set. filename =",
"name of the dataset to for # prediction perfomance analysis. Could be the",
"= 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True, parplot=True, hexbinp=False) #xlims=[0,1], ylims=[0,1])",
"pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of a point in the latent",
"successfully!\") ''' #============ \"\"\" Working with a sample smiles string to reconstruct it",
"[item for item in x_hat_list if item!='None'] print(\"\\n### {} out of 20 compounds",
"for # prediction perfomance analysis. Could be the test set. filename = 'validation_set.csv'",
"properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for",
"molecules to a pdf file as well as CSV using data frame above",
"\"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid molecules verified_x_hat",
"\"\"\" Creating the VAE object and initializing the instance \"\"\" model_DIR = \"./aux_files/\"",
"print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of",
"test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename,",
"VAE object and initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR)",
"= vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular space without verifying its",
"its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep,",
"molecular space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} :",
"VAE object created successfully!\") ''' #============ \"\"\" Working with a sample smiles string",
"#====================== \"\"\" Converting those random representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat,",
"print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:',",
"of drawing parity plot for that component \"\"\" #input_data = string showing the",
"predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat =",
"drawing parity plot for that component \"\"\" #input_data = string showing the location",
"using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction",
"Working with a sample smiles string to reconstruct it and predict its properties",
"the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses =",
"VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============ \"\"\" Working with a sample",
"= vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0]))",
"properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True,",
"sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) #",
"to reconstruct it and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep =",
"vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"###",
"item in x_hat_list if item!='None'] print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat)))",
"item!='None'] print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted",
"df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules",
"# to valid molecules verified_x_hat = [item for item in x_hat_list if item!='None']",
"latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\"",
"generated molecules to a pdf file as well as CSV using data frame",
"#'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True, parplot=True, hexbinp=False)",
"print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:',",
"\"\"\" prediction performance analysis for a component of interest with option of drawing",
"{} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop))",
"= np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random",
"\"\"\" Iteratively sampling from vicinity of a point in the latent space \"\"\"",
"of the dataset to for # prediction perfomance analysis. Could be the test",
"import * #====================== \"\"\" Creating the VAE object and initializing the instance \"\"\"",
"string to reconstruct it and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep",
"num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to a pdf file",
"its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s}",
"{}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"###",
"np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties',",
"\"\"\" Working with a sample smiles string to reconstruct it and predict its",
"= vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular",
"those random representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) #",
"interest with option of drawing parity plot for that component \"\"\" #input_data =",
"z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to",
"sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z",
": {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep)))",
"file as well as CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\",",
"# decoding # to molecular space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep,",
"and name of the dataset to for # prediction perfomance analysis. Could be",
"valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid",
"''' #============ \"\"\" Working with a sample smiles string to reconstruct it and",
"with option of drawing parity plot for that component \"\"\" #input_data = string",
"the dataset to for # prediction perfomance analysis. Could be the test set.",
": {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of",
"\"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated",
"{:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape,",
"{}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property",
"decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to a pdf",
"\"\"\" Saving generated molecules to a pdf file as well as CSV using",
"perfomance analysis. Could be the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples =",
"prediction perfomance analysis. Could be the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples",
"vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular space",
"from vicinity of a point in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep,",
"distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\"",
"\"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting",
"{:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #======================",
"a point in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5,",
"filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235,",
"x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid molecules verified_x_hat =",
"the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #======================",
"component \"\"\" #input_data = string showing the location and name of the dataset",
"standardized=True, verified=True) # decoding # to valid molecules verified_x_hat = [item for item",
": {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\"",
"* #====================== \"\"\" Creating the VAE object and initializing the instance \"\"\" model_DIR",
"string showing the location and name of the dataset to for # prediction",
"of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\"",
"= [item for item in x_hat_list if item!='None'] print(\"\\n### {} out of 20",
"dataset to for # prediction perfomance analysis. Could be the test set. filename",
"a pdf file as well as CSV using data frame above \"\"\" vae.save_gen_mols(df,",
"a component of interest with option of drawing parity plot for that component",
"X_hat[0])) print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s}",
"#====================== \"\"\" Creating the VAE object and initializing the instance \"\"\" model_DIR =",
"\"\"\" #input_data = string showing the location and name of the dataset to",
"that component \"\"\" #input_data = string showing the location and name of the",
": {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with",
"{:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number",
"#====================== \"\"\" Saving generated molecules to a pdf file as well as CSV",
"{:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of a",
"verified=True) # decoding # to valid molecules verified_x_hat = [item for item in",
"well as CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #======================",
"vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for 20",
"object and initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The",
"from vae_model import * #====================== \"\"\" Creating the VAE object and initializing the",
"and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat",
"\"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") '''",
"out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #======================",
"print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for 20 samples",
"Property prediction for 20 samples from multivariate standard normal distribution \"\"\" z_mat =",
"= vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations to valid molecules \"\"\"",
"noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to a pdf file as",
"{:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s}",
"size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations to valid",
"with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props))",
"Saving generated molecules to a pdf file as well as CSV using data",
"''' \"\"\" prediction performance analysis for a component of interest with option of",
"random representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding",
"above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for",
"{:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for 20 samples from",
"to valid molecules verified_x_hat = [item for item in x_hat_list if item!='None'] print(\"\\n###",
"{} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties',",
"molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid molecules",
"space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input',",
"as CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== '''",
"representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding #",
": {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for 20 samples from multivariate",
"vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============ \"\"\" Working with",
"are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from",
"Creating the VAE object and initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae",
"instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\")",
"properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of a point in the",
"location and name of the dataset to for # prediction perfomance analysis. Could",
"properties', predicted_props)) #====================== \"\"\" Property prediction for 20 samples from multivariate standard normal",
"verified=False) # decoding # to molecular space without verifying its validity. predicted_props =",
"performance analysis for a component of interest with option of drawing parity plot",
"initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object",
"compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling",
"as well as CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\")",
"{}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction for 20 samples from multivariate standard",
"X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular space without verifying",
"pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations to valid molecules",
"decoding # to valid molecules verified_x_hat = [item for item in x_hat_list if",
"validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} :",
"Could be the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000",
"'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding #",
"for item in x_hat_list if item!='None'] print(\"\\n### {} out of 20 compounds are",
"plot for that component \"\"\" #input_data = string showing the location and name",
"for that component \"\"\" #input_data = string showing the location and name of",
"= VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============ \"\"\" Working with a",
"object created successfully!\") ''' #============ \"\"\" Working with a sample smiles string to",
"print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} :",
"model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============",
"for a component of interest with option of drawing parity plot for that",
"in x_hat_list if item!='None'] print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"###",
"#====================== ''' \"\"\" prediction performance analysis for a component of interest with option",
"vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to a",
"parity plot for that component \"\"\" #input_data = string showing the location and",
"cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for a component of",
"prediction for 20 samples from multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0,",
"1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations to",
"CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\"",
"vicinity of a point in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500,",
"# prediction perfomance analysis. Could be the test set. filename = 'validation_set.csv' #'validation_set.csv'",
"vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for a component",
"be the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses",
"standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular space without",
"\"\"\" Property prediction for 20 samples from multivariate standard normal distribution \"\"\" z_mat",
"standardized=True, verified=False) # decoding # to molecular space without verifying its validity. predicted_props",
": {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of a point",
"created successfully!\") ''' #============ \"\"\" Working with a sample smiles string to reconstruct",
"#============ \"\"\" Working with a sample smiles string to reconstruct it and predict",
"Converting those random representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True)",
"the location and name of the dataset to for # prediction perfomance analysis.",
"analysis for a component of interest with option of drawing parity plot for",
"to a pdf file as well as CSV using data frame above \"\"\"",
"\"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for a",
"from multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop =",
"{}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {} with norm",
"#====================== \"\"\" Iteratively sampling from vicinity of a point in the latent space",
"sampling from vicinity of a point in the latent space \"\"\" df =",
"20 samples from multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1]))",
"with a sample smiles string to reconstruct it and predict its properties \"\"\"",
"of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props)) #====================== \"\"\" Property prediction",
"np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations",
"it and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True)",
"= vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid molecules verified_x_hat = [item",
"# decoding # to valid molecules verified_x_hat = [item for item in x_hat_list",
"molecules verified_x_hat = [item for item in x_hat_list if item!='None'] print(\"\\n### {} out",
"{:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s} : {}",
"verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity",
"Iteratively sampling from vicinity of a point in the latent space \"\"\" df",
"constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to a pdf file as well",
"= 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding",
"showing the location and name of the dataset to for # prediction perfomance",
"\"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============ \"\"\" Working",
"z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted",
"to molecular space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s}",
"print(\"The VAE object created successfully!\") ''' #============ \"\"\" Working with a sample smiles",
"print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} : {}\\n\\n\".format('Predicted properties', predicted_props))",
"sample smiles string to reconstruct it and predict its properties \"\"\" sample_smiles =",
"z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those",
"print(\"### {:20s} : {} with norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} :",
"predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction',",
"vae.z_to_smiles(z_rep, standardized=True, verified=False) # decoding # to molecular space without verifying its validity.",
"standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"### {:20s} : {}\".format('Reconstruction', X_hat[0])) print(\"### {:20s}",
"predicted_props)) #====================== \"\"\" Property prediction for 20 samples from multivariate standard normal distribution",
"#====================== \"\"\" Property prediction for 20 samples from multivariate standard normal distribution \"\"\"",
"# to molecular space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"###",
"normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True) #======================",
"\"\"\" Converting those random representations to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True,",
"verbose=False) #====================== \"\"\" Saving generated molecules to a pdf file as well as",
"component of interest with option of drawing parity plot for that component \"\"\"",
"800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True, parplot=True, hexbinp=False) #xlims=[0,1], ylims=[0,1]) print(rmses)",
"nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True, parplot=True, hexbinp=False) #xlims=[0,1],",
"set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples,",
"in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False)",
"vae.predict_prop_z(z_mat, standardized=True) #====================== \"\"\" Converting those random representations to valid molecules \"\"\" x_hat_list",
"= vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving generated molecules to",
"if item!='None'] print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} :",
"verified_x_hat = [item for item in x_hat_list if item!='None'] print(\"\\n### {} out of",
"\"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles, standardized=True) X_hat = vae.z_to_smiles(z_rep, standardized=True, verified=False)",
"verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles)) print(\"###",
"norm {:.3f}\".format('Z representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"###",
"multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat,",
"standardized=True) #====================== \"\"\" Converting those random representations to valid molecules \"\"\" x_hat_list =",
"without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True) print(\"### {:20s} : {}\".format('Input', sample_smiles))",
"20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s} : {}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively",
"standard normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop = vae.predict_prop_z(z_mat, standardized=True)",
"of interest with option of drawing parity plot for that component \"\"\" #input_data",
"representation:', z_rep.shape, np.linalg.norm(z_rep))) print(\"### {:20s} : {}\".format('Number of properties', vae.n_props)) print(\"### {:20s} :",
"for 20 samples from multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0, 1,",
"analysis. Could be the test set. filename = 'validation_set.csv' #'validation_set.csv' nsamples = 800",
"pdf file as well as CSV using data frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'],",
"point in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False,",
"option of drawing parity plot for that component \"\"\" #input_data = string showing",
"and initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE",
"valid molecules verified_x_hat = [item for item in x_hat_list if item!='None'] print(\"\\n### {}",
"x_hat_list if item!='None'] print(\"\\n### {} out of 20 compounds are verified!\".format(len(verified_x_hat))) print(\"### {:20s}",
"samples from multivariate standard normal distribution \"\"\" z_mat = np.random.normal(0, 1, size=(20,z_rep.shape[1])) pred_prop",
"a sample smiles string to reconstruct it and predict its properties \"\"\" sample_smiles",
"'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True, parplot=True,",
"#input_data = string showing the location and name of the dataset to for",
"= 'validation_set.csv' #'validation_set.csv' nsamples = 800 #600000 rmses = vae.component_parity_check(model_DIR+filename, ssize=nsamples, seed=235, histplot=True,",
"the instance \"\"\" model_DIR = \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created",
"space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10, noise_norm=0.5, constant_norm=False, verbose=False) #====================== \"\"\" Saving",
"the VAE object and initializing the instance \"\"\" model_DIR = \"./aux_files/\" vae =",
"smiles string to reconstruct it and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1'",
"{}\".format('Predicted properties:', pred_prop)) #====================== \"\"\" Iteratively sampling from vicinity of a point in",
"vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to valid molecules verified_x_hat = [item for",
"of a point in the latent space \"\"\" df = vae.iter_sampling_from_ls(z_rep, decode_attempts=500, num_iter=10,",
"vae_model import * #====================== \"\"\" Creating the VAE object and initializing the instance",
"= \"./aux_files/\" vae = VAE_Model(directory=model_DIR) print(\"The VAE object created successfully!\") ''' #============ \"\"\"",
"reconstruct it and predict its properties \"\"\" sample_smiles = 'OC1=CC=C(C2=C(C3=CC=C(O)C=C3S2)N2C3=CC=C(C=C3C=C2)OCCN2CCCCC2)C=C1' z_rep = vae.smiles_to_z(sample_smiles,",
"out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for a component of interest",
"frame above \"\"\" vae.save_gen_mols(df, cols_of_interest=['comp1','comp2','comp3'], out_file=\"gen_mols.pdf\", out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis",
"= string showing the location and name of the dataset to for #",
"out_dir=\"./test_out/\") #====================== ''' \"\"\" prediction performance analysis for a component of interest with",
"decoding # to molecular space without verifying its validity. predicted_props = vae.predict_prop_z(z_rep, standardized=True)",
"to valid molecules \"\"\" x_hat_list = vae.z_to_smiles(z_mat, standardized=True, verified=True) # decoding # to",
"prediction performance analysis for a component of interest with option of drawing parity"
] |
[
"self.right = right class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:",
"def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or",
"binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None,",
"or root.val == val: return root return self.searchBST(root.right, val) if root.val < val",
"def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right =",
"class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left",
"val=0, left=None, right=None): self.val = val self.left = left self.right = right class",
"left=None, right=None): self.val = val self.left = left self.right = right class Solution:",
"from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val =",
"typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val",
"right class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root",
"is None or root.val == val: return root return self.searchBST(root.right, val) if root.val",
"-> Optional[TreeNode]: if root is None or root.val == val: return root return",
"# Definition for a binary tree node. from typing import Optional class TreeNode:",
"= val self.left = left self.right = right class Solution: def searchBST(self, root:",
"Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left =",
"val self.left = left self.right = right class Solution: def searchBST(self, root: Optional[TreeNode],",
"root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val ==",
"None or root.val == val: return root return self.searchBST(root.right, val) if root.val <",
"import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left",
"left self.right = right class Solution: def searchBST(self, root: Optional[TreeNode], val: int) ->",
"self.val = val self.left = left self.right = right class Solution: def searchBST(self,",
"Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None",
"root is None or root.val == val: return root return self.searchBST(root.right, val) if",
"Definition for a binary tree node. from typing import Optional class TreeNode: def",
"Optional[TreeNode]: if root is None or root.val == val: return root return self.searchBST(root.right,",
"if root is None or root.val == val: return root return self.searchBST(root.right, val)",
"for a binary tree node. from typing import Optional class TreeNode: def __init__(self,",
"int) -> Optional[TreeNode]: if root is None or root.val == val: return root",
"a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0,",
"searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val",
"right=None): self.val = val self.left = left self.right = right class Solution: def",
"= right class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if",
"TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right",
"val: return root return self.searchBST(root.right, val) if root.val < val else self.searchBST(root.left, val)",
"Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val == val:",
"== val: return root return self.searchBST(root.right, val) if root.val < val else self.searchBST(root.left,",
"= left self.right = right class Solution: def searchBST(self, root: Optional[TreeNode], val: int)",
"__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right",
"root.val == val: return root return self.searchBST(root.right, val) if root.val < val else",
"class Solution: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is",
"tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None):",
"self.left = left self.right = right class Solution: def searchBST(self, root: Optional[TreeNode], val:",
"node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val",
"val: int) -> Optional[TreeNode]: if root is None or root.val == val: return"
] |
[
"import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig( provider=\"local\", offline_store_creator=PostgreSQLDataSourceCreator, online_store_creator=PostgreSQLDataSourceCreator, ), ]",
"from feast.infra.offline_stores.contrib.postgres_offline_store.tests.data_source import ( PostgreSQLDataSourceCreator, ) from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS",
"from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig( provider=\"local\", offline_store_creator=PostgreSQLDataSourceCreator, online_store_creator=PostgreSQLDataSourceCreator,",
"feast.infra.offline_stores.contrib.postgres_offline_store.tests.data_source import ( PostgreSQLDataSourceCreator, ) from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS =",
"import ( PostgreSQLDataSourceCreator, ) from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [",
"PostgreSQLDataSourceCreator, ) from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig( provider=\"local\",",
"tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig( provider=\"local\", offline_store_creator=PostgreSQLDataSourceCreator, online_store_creator=PostgreSQLDataSourceCreator, ),",
"( PostgreSQLDataSourceCreator, ) from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig(",
") from tests.integration.feature_repos.integration_test_repo_config import ( IntegrationTestRepoConfig, ) FULL_REPO_CONFIGS = [ IntegrationTestRepoConfig( provider=\"local\", offline_store_creator=PostgreSQLDataSourceCreator,"
] |
[
"b import tokenize import imphook class TokBuf: def __init__(self): self.tokens = [] def",
"self.tokens def spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for",
"yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from",
"nt1[1] == \"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:]",
"# This imphook module implements \"arrow functions\", similar to JavaScript. # (a, b)",
"def empty(self): return not self.tokens def spool(self): yield from self.tokens self.clear() def xform(token_stream):",
"t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not self.tokens def spool(self): yield",
"back to string form # isn't too efficient, but CPython doesn't offer us",
"way to parse # token stream so far, so we have no choice.",
"yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream) nt2 =",
"== \"(\": # We're interested only in the deepest parens. if not tokbuf.empty():",
"== \")\": nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\" and",
"offer us a way to parse # token stream so far, so we",
"We're interested only in the deepest parens. if not tokbuf.empty(): yield from tokbuf.spool()",
"return not self.tokens def spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf =",
"yield from tokbuf.spool() yield t yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t)",
"in token_stream: if t[1] == \"(\": # We're interested only in the deepest",
"we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source, vars(mod)) return",
"# token stream so far, so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline)))",
"This imphook module implements \"arrow functions\", similar to JavaScript. # (a, b) =>",
"tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream) nt2",
"# We're interested only in the deepest parens. if not tokbuf.empty(): yield from",
"nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename): with open(filename,",
"and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP,",
"us a way to parse # token stream so far, so we have",
"b) => a + b ---> lambda a, b: a + b import",
"= [] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not",
"t in token_stream: if t[1] == \"(\": # We're interested only in the",
"self.tokens.clear() def empty(self): return not self.tokens def spool(self): yield from self.tokens self.clear() def",
"# Fairly speaking, tokenizing just to convert back to string form # isn't",
"TokBuf() for t in token_stream: if t[1] == \"(\": # We're interested only",
"yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield t yield nt1 yield nt2",
"JavaScript. # (a, b) => a + b ---> lambda a, b: a",
"# isn't too efficient, but CPython doesn't offer us a way to parse",
"def xform(token_stream): tokbuf = TokBuf() for t in token_stream: if t[1] == \"(\":",
"isn't too efficient, but CPython doesn't offer us a way to parse #",
"from tokbuf.spool() yield t yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else:",
"def spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for t",
"nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\" and nt2[1] ==",
"\">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield",
"self.tokens = [] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return",
"== \"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear()",
"def clear(self): self.tokens.clear() def empty(self): return not self.tokens def spool(self): yield from self.tokens",
"CPython doesn't offer us a way to parse # token stream so far,",
"elif not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename): with open(filename, \"r\")",
"yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield t",
"the deepest parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] ==",
"tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1]",
"def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not self.tokens def",
"hook(modname, filename): with open(filename, \"r\") as f: # Fairly speaking, tokenizing just to",
"else: yield t def hook(modname, filename): with open(filename, \"r\") as f: # Fairly",
"append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not self.tokens def spool(self):",
"tokenize import imphook class TokBuf: def __init__(self): self.tokens = [] def append(self, t):",
"imphook module implements \"arrow functions\", similar to JavaScript. # (a, b) => a",
"yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename): with",
"f: # Fairly speaking, tokenizing just to convert back to string form #",
"tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream) nt2 = next(token_stream) if",
"deepest parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\":",
"functions\", similar to JavaScript. # (a, b) => a + b ---> lambda",
"for t in token_stream: if t[1] == \"(\": # We're interested only in",
"not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream)",
"but CPython doesn't offer us a way to parse # token stream so",
"interested only in the deepest parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t)",
"next(token_stream) if nt1[1] == \"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield",
"nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\")",
"a, b: a + b import tokenize import imphook class TokBuf: def __init__(self):",
"def __init__(self): self.tokens = [] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def",
"empty(self): return not self.tokens def spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf",
"\":\") else: yield from tokbuf.spool() yield t yield nt1 yield nt2 elif not",
"\"r\") as f: # Fairly speaking, tokenizing just to convert back to string",
"Fairly speaking, tokenizing just to convert back to string form # isn't too",
"similar to JavaScript. # (a, b) => a + b ---> lambda a,",
"next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\" and nt2[1] == \">\": yield",
"\"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield",
"yield t def hook(modname, filename): with open(filename, \"r\") as f: # Fairly speaking,",
"clear(self): self.tokens.clear() def empty(self): return not self.tokens def spool(self): yield from self.tokens self.clear()",
"stream so far, so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod =",
"= next(token_stream) if nt1[1] == \"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\")",
"+ b ---> lambda a, b: a + b import tokenize import imphook",
"(a, b) => a + b ---> lambda a, b: a + b",
"open(filename, \"r\") as f: # Fairly speaking, tokenizing just to convert back to",
"module implements \"arrow functions\", similar to JavaScript. # (a, b) => a +",
"parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1",
"self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for t in token_stream: if t[1]",
"yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname,",
"else: yield from tokbuf.spool() yield t yield nt1 yield nt2 elif not tokbuf.empty():",
"import imphook class TokBuf: def __init__(self): self.tokens = [] def append(self, t): self.tokens.append(t)",
"efficient, but CPython doesn't offer us a way to parse # token stream",
"a + b ---> lambda a, b: a + b import tokenize import",
"tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename): with open(filename, \"r\") as f:",
"t yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t def",
"parse # token stream so far, so we have no choice. source =",
"from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 = next(token_stream) nt2 = next(token_stream)",
"lambda a, b: a + b import tokenize import imphook class TokBuf: def",
"just to convert back to string form # isn't too efficient, but CPython",
"import tokenize import imphook class TokBuf: def __init__(self): self.tokens = [] def append(self,",
"tokenizing just to convert back to string form # isn't too efficient, but",
"<reponame>pfalcon/python-imphook<gh_stars>10-100 # This imphook module implements \"arrow functions\", similar to JavaScript. # (a,",
"yield t yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t",
"in the deepest parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1]",
"far, so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source,",
"== \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else:",
"+ b import tokenize import imphook class TokBuf: def __init__(self): self.tokens = []",
"def hook(modname, filename): with open(filename, \"r\") as f: # Fairly speaking, tokenizing just",
"tokbuf = TokBuf() for t in token_stream: if t[1] == \"(\": # We're",
"\")\": nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\" and nt2[1]",
"tokbuf.append(t) else: yield t def hook(modname, filename): with open(filename, \"r\") as f: #",
"class TokBuf: def __init__(self): self.tokens = [] def append(self, t): self.tokens.append(t) def clear(self):",
"so far, so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname)",
"__init__(self): self.tokens = [] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self):",
"tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield t yield nt1 yield",
"nt2 = next(token_stream) if nt1[1] == \"=\" and nt2[1] == \">\": yield (tokenize.NAME,",
"too efficient, but CPython doesn't offer us a way to parse # token",
"from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield t yield",
"t[1] == \"(\": # We're interested only in the deepest parens. if not",
"[] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not self.tokens",
"only in the deepest parens. if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif",
"spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for t in",
"implements \"arrow functions\", similar to JavaScript. # (a, b) => a + b",
"filename): with open(filename, \"r\") as f: # Fairly speaking, tokenizing just to convert",
"convert back to string form # isn't too efficient, but CPython doesn't offer",
"to parse # token stream so far, so we have no choice. source",
"= next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\" and nt2[1] == \">\":",
"tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool() yield t yield nt1",
"with open(filename, \"r\") as f: # Fairly speaking, tokenizing just to convert back",
"self.clear() def xform(token_stream): tokbuf = TokBuf() for t in token_stream: if t[1] ==",
"not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename): with open(filename, \"r\") as",
"xform(token_stream): tokbuf = TokBuf() for t in token_stream: if t[1] == \"(\": #",
"=> a + b ---> lambda a, b: a + b import tokenize",
"if not tokbuf.empty(): yield from tokbuf.spool() tokbuf.append(t) elif t[1] == \")\": nt1 =",
"# (a, b) => a + b ---> lambda a, b: a +",
"yield from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for t in token_stream:",
"---> lambda a, b: a + b import tokenize import imphook class TokBuf:",
"\"arrow functions\", similar to JavaScript. # (a, b) => a + b --->",
"a + b import tokenize import imphook class TokBuf: def __init__(self): self.tokens =",
"b ---> lambda a, b: a + b import tokenize import imphook class",
"speaking, tokenizing just to convert back to string form # isn't too efficient,",
"from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf() for t in token_stream: if",
"to string form # isn't too efficient, but CPython doesn't offer us a",
"to convert back to string form # isn't too efficient, but CPython doesn't",
"= TokBuf() for t in token_stream: if t[1] == \"(\": # We're interested",
"\"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield",
"elif t[1] == \")\": nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1] ==",
"tokbuf.spool() yield t yield nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield",
"a way to parse # token stream so far, so we have no",
"to JavaScript. # (a, b) => a + b ---> lambda a, b:",
"as f: # Fairly speaking, tokenizing just to convert back to string form",
"b: a + b import tokenize import imphook class TokBuf: def __init__(self): self.tokens",
"self.tokens.append(t) def clear(self): self.tokens.clear() def empty(self): return not self.tokens def spool(self): yield from",
"(tokenize.OP, \":\") else: yield from tokbuf.spool() yield t yield nt1 yield nt2 elif",
"imphook class TokBuf: def __init__(self): self.tokens = [] def append(self, t): self.tokens.append(t) def",
"if t[1] == \"(\": # We're interested only in the deepest parens. if",
"so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source, vars(mod))",
"form # isn't too efficient, but CPython doesn't offer us a way to",
"token stream so far, so we have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod",
"t[1] == \")\": nt1 = next(token_stream) nt2 = next(token_stream) if nt1[1] == \"=\"",
"(tokenize.NAME, \"lambda\") yield from tokbuf.tokens[1:] tokbuf.clear() yield (tokenize.OP, \":\") else: yield from tokbuf.spool()",
"doesn't offer us a way to parse # token stream so far, so",
"if nt1[1] == \"=\" and nt2[1] == \">\": yield (tokenize.NAME, \"lambda\") yield from",
"TokBuf: def __init__(self): self.tokens = [] def append(self, t): self.tokens.append(t) def clear(self): self.tokens.clear()",
"choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source, vars(mod)) return mod imphook.add_import_hook(hook, (\".py\",))",
"have no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source, vars(mod)) return mod",
"t def hook(modname, filename): with open(filename, \"r\") as f: # Fairly speaking, tokenizing",
"\"(\": # We're interested only in the deepest parens. if not tokbuf.empty(): yield",
"token_stream: if t[1] == \"(\": # We're interested only in the deepest parens.",
"nt1 yield nt2 elif not tokbuf.empty(): tokbuf.append(t) else: yield t def hook(modname, filename):",
"string form # isn't too efficient, but CPython doesn't offer us a way",
"no choice. source = tokenize.untokenize(xform(tokenize.generate_tokens(f.readline))) mod = type(imphook)(modname) exec(source, vars(mod)) return mod imphook.add_import_hook(hook,",
"not self.tokens def spool(self): yield from self.tokens self.clear() def xform(token_stream): tokbuf = TokBuf()"
] |
[
"class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion) admin.site.register(Lote)",
"[ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion) admin.site.register(Lote) #admin.site.register(Manzano,ManzanoAdmin) admin.site.register(Manzano) admin.site.register(Medida) admin.site.register(Distrito)",
"inlines = [ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion) admin.site.register(Lote) #admin.site.register(Manzano,ManzanoAdmin) admin.site.register(Manzano)",
"[ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude = ('lotes',)",
"from .models import Manzano from .models import Medida from .models import Distrito \"\"\"",
"import Manzano from .models import Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline):",
"import Ubicacion from .models import Lote from .models import Manzano from .models import",
"class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines,",
"Lote from .models import Manzano from .models import Medida from .models import Distrito",
".models import Ubicacion from .models import Lote from .models import Manzano from .models",
"= [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude =",
"django.contrib import admin from .models import Ubicacion from .models import Lote from .models",
"= [ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion) admin.site.register(Lote) #admin.site.register(Manzano,ManzanoAdmin) admin.site.register(Manzano) admin.site.register(Medida)",
"Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [",
".models import Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through",
"import Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class",
"inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude",
"import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [",
"Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin):",
"model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines",
"import Lote from .models import Manzano from .models import Medida from .models import",
"admin from .models import Ubicacion from .models import Lote from .models import Manzano",
"from .models import Ubicacion from .models import Lote from .models import Manzano from",
"ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion) admin.site.register(Lote) #admin.site.register(Manzano,ManzanoAdmin)",
"from .models import Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model =",
"Ubicacion from .models import Lote from .models import Manzano from .models import Medida",
"from .models import Lote from .models import Manzano from .models import Medida from",
"Manzano from .models import Medida from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model",
"Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines,",
"class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class",
"<filename>apps/terreno/admin.py from django.contrib import admin from .models import Ubicacion from .models import Lote",
"lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude = ('lotes',) \"\"\"",
".models import Lote from .models import Manzano from .models import Medida from .models",
"\"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ]",
"= Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines =",
"] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] exclude = ('lotes',) \"\"\" admin.site.register(Ubicacion)",
"lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin):",
"import admin from .models import Ubicacion from .models import Lote from .models import",
"LoteAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ] class ManzanoAdmin(admin.ModelAdmin): inlines = [ lotesInlines, ]",
".models import Manzano from .models import Medida from .models import Distrito \"\"\" class",
"from django.contrib import admin from .models import Ubicacion from .models import Lote from",
".models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines =",
"from .models import Distrito \"\"\" class lotesInlines(admin.TabularInline): model = Manzano.lotes.through class LoteAdmin(admin.ModelAdmin): inlines"
] |
[
"'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end']",
"# Possible methods to fill nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median'",
"time features available in pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month',",
"all strings with constants # Column types (in context of data science) TYPE",
"'datetime' } # List of date time features available in pandas date time",
"pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear',",
"} # Possible methods to fill infs in numerical columns FILL_INF_METHODS = {",
"'is_year_start', 'is_year_end'] } # Possible methods to fill nans in numerical columns FILL_NAN_METHODS",
"{ 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start',",
"'is_year_end'] } # Possible methods to fill nans in numerical columns FILL_NAN_METHODS =",
"TODO: Substitue all strings with constants # Column types (in context of data",
"'categorical', 'datetime' } # List of date time features available in pandas date",
"'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods",
"# TODO: Substitue all strings with constants # Column types (in context of",
"'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to fill nans in",
"date time features available in pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year',",
"methods to fill nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } #",
"nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to",
"{ 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs in numerical columns FILL_INF_METHODS",
"date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week',",
"science) TYPE = { 'numerical', 'categorical', 'datetime' } # List of date time",
"time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek',",
"'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] }",
"data science) TYPE = { 'numerical', 'categorical', 'datetime' } # List of date",
"'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end',",
"'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } #",
"} # Possible methods to fill nans in numerical columns FILL_NAN_METHODS = {",
"Possible methods to fill infs in numerical columns FILL_INF_METHODS = { 'MAXMIN':'maxmin','NAN':'nan' }",
"'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible",
"features available in pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day',",
"in pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear',",
"DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start',",
"List of date time features available in pandas date time columns DATE_TIME_FEATURES =",
"# Column types (in context of data science) TYPE = { 'numerical', 'categorical',",
"'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to fill",
"fill nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods",
"= { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs in numerical columns",
"available in pandas date time columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour',",
"types (in context of data science) TYPE = { 'numerical', 'categorical', 'datetime' }",
"(in context of data science) TYPE = { 'numerical', 'categorical', 'datetime' } #",
"in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill",
"Substitue all strings with constants # Column types (in context of data science)",
"'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to",
"columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs in",
"'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs in numerical columns FILL_INF_METHODS =",
"'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to fill nans in numerical",
"constants # Column types (in context of data science) TYPE = { 'numerical',",
"of date time features available in pandas date time columns DATE_TIME_FEATURES = {",
"Column types (in context of data science) TYPE = { 'numerical', 'categorical', 'datetime'",
"TYPE = { 'numerical', 'categorical', 'datetime' } # List of date time features",
"columns DATE_TIME_FEATURES = { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'],",
"{ 'numerical', 'categorical', 'datetime' } # List of date time features available in",
"of data science) TYPE = { 'numerical', 'categorical', 'datetime' } # List of",
"with constants # Column types (in context of data science) TYPE = {",
"'numerical', 'categorical', 'datetime' } # List of date time features available in pandas",
"# Possible methods to fill infs in numerical columns FILL_INF_METHODS = { 'MAXMIN':'maxmin','NAN':'nan'",
"strings with constants # Column types (in context of data science) TYPE =",
"FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs in numerical",
"} # List of date time features available in pandas date time columns",
"'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start',",
"'BOOLEANS':['is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to fill nans",
"'is_quarter_end', 'is_year_start', 'is_year_end'] } # Possible methods to fill nans in numerical columns",
"Possible methods to fill nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' }",
"numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible methods to fill infs",
"= { 'numerical', 'categorical', 'datetime' } # List of date time features available",
"context of data science) TYPE = { 'numerical', 'categorical', 'datetime' } # List",
"to fill nans in numerical columns FILL_NAN_METHODS = { 'MEAN':'mean','MEDIAN':'median' } # Possible",
"= { 'NUMERICS':['year', 'month', 'day', 'hour', 'dayofyear', 'weekofyear', 'week', 'dayofweek', 'quarter'], 'BOOLEANS':['is_month_start', 'is_month_end',",
"# List of date time features available in pandas date time columns DATE_TIME_FEATURES"
] |
[
"38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy))",
"= [] sail = [] rudder = [] alphaw = [] pitchvar =",
"axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway",
"* 100 for n in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw",
"left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax)",
"plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\")",
"row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13],",
"ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57,",
"180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1],",
"[] heading = [] leeway = [] sail = [] rudder = []",
"row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi /",
"(deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder",
"x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. /",
"+ row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 +",
"latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0], label='x less bias')",
"\"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax)",
"[] pitchvar = [] wind_speed = [] true_alphaw = [] true_wind_speed = []",
"label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir =",
"x - x[0], label='x less bias') ax.plot(t, y - y[0], label='y less bias')",
"name, ax, maxy=50): t = data[:, 0] x = data[:, starti+0] y =",
"[] vx = [] vy = [] speed = [] t = []",
"numpy as np import sys from matplotlib import pyplot as plt def norm_theta(theta):",
"row in data: if row[0] < 4000: continue for i in range(len(row)): if",
"'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while",
"27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\",",
"Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position",
"/ np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2]",
"[] orig_heel = [] orig_speed = [] for row in data: if row[0]",
"[] heel = [] pitch = [] heading = [] leeway = []",
"if row[0] > 4485: # break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4]",
"** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat",
"= data[:, starti+0] y = data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111,",
"if row[0] < 4000: continue for i in range(len(row)): if abs(row[i]) > 1e5:",
"180. / np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi)",
"maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y = []",
"label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100",
"Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching",
"-len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) *",
"[] vy = [] speed = [] t = [] yaw = []",
"plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail",
"label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for n in pitchvar],",
"continue for i in range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\") #",
"pitch, label='Pitch') axyh.plot(t, [n * 100 for n in pitchvar], label='Pitch Stddev *",
"# plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y",
"Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\")",
"theta -= 2 * np.pi while (theta < -np.pi): theta += 2 *",
"starti, name, ax, maxy=50): t = data[:, 0] x = data[:, starti+0] y",
"row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y,",
"wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper",
"orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) *",
"= [] true_alphaw = [] true_wind_speed = [] heading_cmd = [] rudder_mode =",
"label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True",
"= data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\"",
"ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42,",
"* 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209,",
"label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x =",
"label='Pitch') axyh.plot(t, [n * 100 for n in pitchvar], label='Pitch Stddev * 100')",
"colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure()",
"Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw,",
"vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat",
"axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t,",
"data: if row[0] < 4000: continue for i in range(len(row)): if abs(row[i]) >",
"z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = []",
"right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original",
"100 for n in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw =",
"Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t,",
"[] leeway = [] sail = [] rudder = [] alphaw = []",
"pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180.",
"'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\",",
"if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind",
"# break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180. / np.pi)",
"true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail",
"Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data,",
"(upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths of",
"axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode,",
"axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel,",
"t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) *",
"(deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths of a meter /",
"np.pi): theta -= 2 * np.pi while (theta < -np.pi): theta += 2",
"ax.plot(t, x - x[0], label='x less bias') ax.plot(t, y - y[0], label='y less",
"\"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax)",
"<filename>sim/python/plot_logsim.py #!/usr/bin/python3 import numpy as np import sys from matplotlib import pyplot as",
"np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi)",
"(m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw,",
"plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y =",
"y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy,",
"(tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111,",
"Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r',",
"axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel');",
"= max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1],",
"\"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax)",
"'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle')",
"screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\")",
"label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam",
"# if row[0] > 4485: # break t.append(row[0]) sail.append(row[3] * 180. / np.pi)",
"pitch = [] heading = [] leeway = [] sail = [] rudder",
"true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\")",
"4000: continue for i in range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\")",
"true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16]",
"orig_speed = [] for row in data: if row[0] < 4000: continue for",
"/ np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6])",
"right') plt.title('Boat data while beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind",
"rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel,",
"\"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax)",
"x = [] y = [] vx = [] vy = [] speed",
"/ np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. /",
"label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed",
"axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy)",
"axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--',",
"Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\")",
"-= 2 * np.pi while (theta < -np.pi): theta += 2 * np.pi",
"heading_cmd = [] rudder_mode = [] orig_yaw = [] orig_heel = [] orig_speed",
"label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) *",
"-np.pi): theta += 2 * np.pi return theta def plot_vec(d, starti, name, ax,",
"/ 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1]",
"heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n",
"Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data,",
"label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*',",
"label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper",
"33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\",",
"plot_vec(d, starti, name, ax, maxy=50): t = data[:, 0] x = data[:, starti+0]",
"np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9])",
"label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir",
"and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel,",
"a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t,",
"axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper",
"plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw,",
"\"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax)",
"Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths",
"axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c',",
"theta += 2 * np.pi return theta def plot_vec(d, starti, name, ax, maxy=50):",
"sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel')",
"orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.',",
"label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y',",
"= [] vy = [] speed = [] t = [] yaw =",
"0] x = data[:, starti+0] y = data[:, starti+1] z = data[:, starti+2]",
"of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax)",
"heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle')",
"180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:]))",
"-76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx,",
"/ np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615,",
"[] orig_speed = [] for row in data: if row[0] < 4000: continue",
"true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111,",
"data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\")",
"= np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y = [] vx = []",
"2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2))",
"plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net",
"close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and",
"plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent",
"Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data,",
"= [] t = [] yaw = [] heel = [] pitch =",
"(deg)\\n Boat Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure()",
"sail = [] rudder = [] alphaw = [] pitchvar = [] wind_speed",
"[] speed = [] t = [] yaw = [] heel = []",
"= [] speed = [] t = [] yaw = [] heel =",
"plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net",
"data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\")",
"vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors",
"label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T +",
"> 4485: # break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180.",
"hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway",
"np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig",
"plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\"",
"x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend()",
"plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0],",
"axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for",
"and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat",
"plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw')",
"[38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy,",
"data[:, 0] x = data[:, starti+0] y = data[:, starti+1] z = data[:,",
"* 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b',",
"[] rudder_mode = [] orig_yaw = [] orig_heel = [] orig_speed = []",
"* 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100, -len(pitch))",
"axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t,",
"/ np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7])",
"axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t,",
"plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data",
"+= 2 * np.pi return theta def plot_vec(d, starti, name, ax, maxy=50): t",
"plt def norm_theta(theta): while (theta > np.pi): theta -= 2 * np.pi while",
"- x[0], label='x less bias') ax.plot(t, y - y[0], label='y less bias') ax2",
"'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)')",
"starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t,",
"z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y,",
":] x = [] y = [] vx = [] vy = []",
"= [] alphaw = [] pitchvar = [] wind_speed = [] true_alphaw =",
"Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left')",
"45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\",",
"np import sys from matplotlib import pyplot as plt def norm_theta(theta): while (theta",
"np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) *",
"ax, maxy=50): t = data[:, 0] x = data[:, starti+0] y = data[:,",
"2 + row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10)",
"for i in range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\") # if",
"np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) *",
"= [] yaw = [] heel = [] pitch = [] heading =",
"180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) * 180. /",
"plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw')",
"'*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat",
"axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27,",
"Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0,",
"axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent",
"plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") #",
"(deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0], label='x less",
"np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi)",
"+ row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x,",
"(m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh",
"ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39,",
"orig_yaw = [] orig_heel = [] orig_speed = [] for row in data:",
"label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx,",
"x = data[:, starti+0] y = data[:, starti+1] z = data[:, starti+2] plt.figure()",
"2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\")",
"plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0], label='x less bias') ax.plot(t,",
"matplotlib import pyplot as plt def norm_theta(theta): while (theta > np.pi): theta -=",
"2 * np.pi return theta def plot_vec(d, starti, name, ax, maxy=50): t =",
"'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed)",
"axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed,",
"/ np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20])",
"while (theta < -np.pi): theta += 2 * np.pi return theta def plot_vec(d,",
"heading = [] leeway = [] sail = [] rudder = [] alphaw",
"= [] rudder = [] alphaw = [] pitchvar = [] wind_speed =",
"180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180.",
"and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend()",
"= [] y = [] vx = [] vy = [] speed =",
"ax = plt.subplot(111) ax.plot(t, x - x[0], label='x less bias') ax.plot(t, y -",
"label='x less bias') ax.plot(t, y - y[0], label='y less bias') ax2 = ax.twinx()",
"* 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. /",
"label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch,",
"[] heading_cmd = [] rudder_mode = [] orig_yaw = [] orig_heel = []",
"yaw = [] heel = [] pitch = [] heading = [] leeway",
"speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed",
"rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180.",
"vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t,",
"rudder = [] alphaw = [] pitchvar = [] wind_speed = [] true_alphaw",
"'m', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail,",
"label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax)",
"orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100,",
"* 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) * 180.",
"orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel')",
"180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi)",
"meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed,",
"position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0], label='x",
"= plt.subplot(111) ax.plot(t, x - x[0], label='x less bias') ax.plot(t, y - y[0],",
"* np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. /",
"100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading')",
"i in range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\") # if row[0]",
"wind_speed = [] true_alphaw = [] true_wind_speed = [] heading_cmd = [] rudder_mode",
"'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading",
"wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12]",
"plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net Torque\", ax) ax.set_xlim([4000, 4500]) plt.show()",
"y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:,",
"-76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y,",
"left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw,",
"heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.)",
"'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind",
"axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t,",
"right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33,",
"'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder",
"= [] vx = [] vy = [] speed = [] t =",
"orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180.",
"ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh =",
"axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original",
"< 4000: continue for i in range(len(row)): if abs(row[i]) > 1e5: row[i] =",
"y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi)",
"(deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x",
"[] pitch = [] heading = [] leeway = [] sail = []",
"pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10])",
"ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48,",
"Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed",
"[] for row in data: if row[0] < 4000: continue for i in",
"label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax)",
"leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t,",
"sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t,",
"51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net Torque\",",
"row[0] < 4000: continue for i in range(len(row)): if abs(row[i]) > 1e5: row[i]",
"< -np.pi): theta += 2 * np.pi return theta def plot_vec(d, starti, name,",
"import numpy as np import sys from matplotlib import pyplot as plt def",
"in data: if row[0] < 4000: continue for i in range(len(row)): if abs(row[i])",
"axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n",
"wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True",
"-76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False:",
"Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail')",
"heel = [] pitch = [] heading = [] leeway = [] sail",
"row[0] > 4485: # break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] *",
"10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365,",
"rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx()",
"Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure()",
"plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel",
"axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and close hauled') axyaw.set_ylabel('Heading",
"plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting",
"vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] -",
"ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind",
"label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--',",
"y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left",
"orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi",
"ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed,",
"(Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg",
"def plot_vec(d, starti, name, ax, maxy=50): t = data[:, 0] x = data[:,",
"sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind",
"in range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\") # if row[0] >",
"'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t,",
"Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx();",
"[] alphaw = [] pitchvar = [] wind_speed = [] true_alphaw = []",
"axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind",
"* 180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. /",
"sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True",
"30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\",",
"\"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax)",
"* 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed')",
"axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--',",
"(theta < -np.pi): theta += 2 * np.pi return theta def plot_vec(d, starti,",
"** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] **",
"import pyplot as plt def norm_theta(theta): while (theta > np.pi): theta -= 2",
"ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51,",
"axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data,",
"import sys from matplotlib import pyplot as plt def norm_theta(theta): while (theta >",
"'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--',",
"180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] **",
"np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126],",
"less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy')",
"range(len(row)): if abs(row[i]) > 1e5: row[i] = float(\"nan\") # if row[0] > 4485:",
"180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373,",
"represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax",
"Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10,",
"abs(row[i]) > 1e5: row[i] = float(\"nan\") # if row[0] > 4485: # break",
"for n in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111,",
"axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\",",
"speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1])",
"np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi)",
"label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle')",
"'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t,",
"plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel",
"np.pi while (theta < -np.pi): theta += 2 * np.pi return theta def",
"#axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder')",
"38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx,",
"'b', label=\"Apparent Wind Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind",
"Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t,",
"y - y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx')",
"sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t,",
"Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t,",
"label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig",
"[] y = [] vx = [] vy = [] speed = []",
"= [] orig_heel = [] orig_speed = [] for row in data: if",
"vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) *",
"/ np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15] * 180. /",
"= [] heading = [] leeway = [] sail = [] rudder =",
"Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw,",
"Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t,",
"[] true_wind_speed = [] heading_cmd = [] rudder_mode = [] orig_yaw = []",
"rudder_mode = [] orig_yaw = [] orig_heel = [] orig_speed = [] for",
"- y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t,",
"def norm_theta(theta): while (theta > np.pi): theta -= 2 * np.pi while (theta",
"yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel,",
"pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T",
"ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t,",
"sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180.",
"np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] **",
"label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-',",
"axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths of a meter / sec)')",
"= 0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths of a",
"orig_heel = [] orig_speed = [] for row in data: if row[0] <",
"vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows",
"label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\",",
"= data[:, 0] x = data[:, starti+0] y = data[:, starti+1] z =",
"axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for n in pitchvar], label='Pitch Stddev",
"in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T,",
"velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax =",
"** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] **",
"'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed,",
"180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi)",
"label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder,",
"label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode')",
"(m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\")",
"data[:, starti+0] y = data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax)",
"[] true_alphaw = [] true_wind_speed = [] heading_cmd = [] rudder_mode = []",
"[] rudder = [] alphaw = [] pitchvar = [] wind_speed = []",
"data while beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind =",
"np.pi return theta def plot_vec(d, starti, name, ax, maxy=50): t = data[:, 0]",
"n in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure() axyaw = plt.subplot(111, sharex=ax)",
"plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder",
"Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data,",
"'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t,",
"* 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. /",
"= [] orig_yaw = [] orig_heel = [] orig_speed = [] for row",
"> 1e5: row[i] = float(\"nan\") # if row[0] > 4485: # break t.append(row[0])",
"= [] heel = [] pitch = [] heading = [] leeway =",
"plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771,",
"leeway = [] sail = [] rudder = [] alphaw = [] pitchvar",
"Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat",
"true_alphaw = [] true_wind_speed = [] heading_cmd = [] rudder_mode = [] orig_yaw",
"** 2 + row[13] ** 2)) heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] *",
"plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull",
"norm_theta(theta): while (theta > np.pi): theta -= 2 * np.pi while (theta <",
"maxy=50): t = data[:, 0] x = data[:, starti+0] y = data[:, starti+1]",
"sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\")",
"Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and",
"plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y = [] vx",
"38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\")",
"Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net Torque\", ax) ax.set_xlim([4000,",
"= axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right')",
"heading_cmd.append(row[15] * 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516,",
"less bias') ax.plot(t, y - y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t,",
"Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30,",
"36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\",",
"bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t,",
"axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and close",
"axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel');",
"alphaw = [] pitchvar = [] wind_speed = [] true_alphaw = [] true_wind_speed",
"plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111)",
"* 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))*",
"plt.title('Boat data while beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind",
"x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy,",
"0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind",
"yaw[-1]) * np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180.",
"180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi)",
"axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder =",
"180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15] * 180.",
"axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k', label='Boat Speed')",
"and Leeway (deg)\\n Boat Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)')",
"2 + row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2",
"10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data",
"axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left') axwinddir.legend(loc='upper",
"pitchvar = [] wind_speed = [] true_alphaw = [] true_wind_speed = [] heading_cmd",
"38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed",
"plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel, 'g',",
"vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on",
"+ 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent",
"plt.figure() ax = plt.subplot(111) ax.plot(t, x - x[0], label='x less bias') ax.plot(t, y",
"t = data[:, 0] x = data[:, starti+0] y = data[:, starti+1] z",
"Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data,",
"true_alphaw, 'm', label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t,",
"while beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0)",
"/ np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21])",
"vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1]",
"Heel, and Leeway (deg)\\n Boat Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time",
"= data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\"",
"starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t,",
"= [] orig_speed = [] for row in data: if row[0] < 4000:",
"axyh.plot(t, [n * 100 for n in pitchvar], label='Pitch Stddev * 100') axyh.legend()",
"= [] leeway = [] sail = [] rudder = [] alphaw =",
"theta def plot_vec(d, starti, name, ax, maxy=50): t = data[:, 0] x =",
"* 180. / np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5]) * 180. /",
"np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart =",
"np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g',",
"Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data,",
"'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed (m/s)\") axwinddir",
"[] t = [] yaw = [] heel = [] pitch = []",
"= [] heading_cmd = [] rudder_mode = [] orig_yaw = [] orig_heel =",
"Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t,",
"'m', label='Sail') axrudder.plot(t, heel, 'c', label='Heel'); axrudder.plot(t, orig_heel, 'c--', label='Orig Heel'); axrudder.plot(t, leeway,",
"on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position (deg",
"0) (deg)') axrudder.set_ylabel('Rudder, Heel, and Leeway (deg)\\n Boat Speed (tenths of a meter",
"(theta > np.pi): theta -= 2 * np.pi while (theta < -np.pi): theta",
"[] sail = [] rudder = [] alphaw = [] pitchvar = []",
"= [] pitch = [] heading = [] leeway = [] sail =",
"Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for n in pitchvar], label='Pitch",
"row[2] ** 2)) true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13]",
"as np import sys from matplotlib import pyplot as plt def norm_theta(theta): while",
"row[i] = float(\"nan\") # if row[0] > 4485: # break t.append(row[0]) sail.append(row[3] *",
"vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1]) * 180. / np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) *",
"Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind =",
"/ np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8])",
"ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--',",
"* 180. / np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11])",
"if abs(row[i]) > 1e5: row[i] = float(\"nan\") # if row[0] > 4485: #",
"data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y = [] vx =",
"np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) *",
"np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25],",
"4485: # break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180. /",
"False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is",
"= float(\"nan\") # if row[0] > 4485: # break t.append(row[0]) sail.append(row[3] * 180.",
"= [] pitchvar = [] wind_speed = [] true_alphaw = [] true_wind_speed =",
"= plt.subplot(111, sharex=ax) axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig",
"* 180. / np.pi) rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533,",
"plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :]",
"ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)')",
"ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed')",
"beam reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)')",
"= ax.twinx() ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*',",
"true_wind_speed = [] heading_cmd = [] rudder_mode = [] orig_yaw = [] orig_heel",
"rudder_mode.append(row[16] * 10) plt.plot(x, y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278,",
"y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data =",
"while (theta > np.pi): theta -= 2 * np.pi while (theta < -np.pi):",
"blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y",
"vy = [] speed = [] t = [] yaw = [] heel",
"ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45,",
"pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26]))",
"-76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if False: plt.quiver(x,",
"(sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed",
"np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2],",
"plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull",
"t = [] yaw = [] heel = [] pitch = [] heading",
"alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*',",
"- yaw[-1]) * np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) *",
"plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors represent",
"= plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw') axyh.plot(t, orig_yaw, 'b--', label='Original Yaw') axyh.plot(t, heel,",
"reaching and close hauled') axyaw.set_ylabel('Heading and Apparent Wind (upwind = 0) (deg)') axrudder.set_ylabel('Rudder,",
"Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data,",
"* 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat",
"axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b', label=\"Apparent Wind Speed",
"vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t, wind_speed,",
"sys from matplotlib import pyplot as plt def norm_theta(theta): while (theta > np.pi):",
"Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax) plot_vec(data,",
"ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net Torque\", ax) ax.set_xlim([4000, 4500])",
"position (deg longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t,",
"plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t,",
"bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\") plt.ylabel(\"Y position",
"np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x = [] y = [] vx = [] vy",
"label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t,",
"orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for n",
"Boat Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind",
"leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) * 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1])",
"ax.plot(t, y - y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx, 'c*',",
"ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54,",
"= [] rudder_mode = [] orig_yaw = [] orig_heel = [] orig_speed =",
"* 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180. /",
"as plt def norm_theta(theta): while (theta > np.pi): theta -= 2 * np.pi",
"= [] for row in data: if row[0] < 4000: continue for i",
"ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left')",
"* 180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2",
"10, 'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45,",
"plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X",
"(m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper left')",
"vx = [] vy = [] speed = [] t = [] yaw",
"'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n * 100 for n in",
"48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\",",
"label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z, label=name+\" z\") # plt.ylim(-maxy, maxy)",
"yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) * 180.",
"Speed (m/s)\") axwinddir = axwind.twinx(); axwinddir.plot(t, true_alphaw, 'c', label=\"True Wind Dir (deg)\") axwind.legend(loc='upper",
"\"Hull Force\", ax) plot_vec(data, 39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax)",
"return theta def plot_vec(d, starti, name, ax, maxy=50): t = data[:, 0] x",
"starti+0] y = data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t,",
"max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1])) orig_speed.append(np.hypot(row[25], row[26])) heading.append(np.arctan2(vy[-1], vx[-1])",
"/ np.pi) leeway.append(norm_theta((heading[-1] - yaw[-1]) * np.pi / 180.) * 180. / np.pi)",
"Yaw') axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch')",
"/ sec)') axyaw.set_xlabel('Time (sec)') plt.grid() plt.figure() axwind = plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r',",
"Leeway (deg)\\n Boat Speed (tenths of a meter / sec)') axyaw.set_xlabel('Time (sec)') plt.grid()",
"from matplotlib import pyplot as plt def norm_theta(theta): while (theta > np.pi): theta",
"* np.pi while (theta < -np.pi): theta += 2 * np.pi return theta",
"label='speed') ax2.plot(t, wind_speed, label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper",
"ax2.plot(t, vx, 'c*', label='vx') ax2.plot(t, vy, 'r*', label='vy') ax2.plot(t, speed, 'g*', label='speed') ax2.plot(t,",
"float(\"nan\") # if row[0] > 4485: # break t.append(row[0]) sail.append(row[3] * 180. /",
"[] wind_speed = [] true_alphaw = [] true_wind_speed = [] heading_cmd = []",
"45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and close hauled')",
"x[0], label='x less bias') ax.plot(t, y - y[0], label='y less bias') ax2 =",
"delimiter=',')[:, :] x = [] y = [] vx = [] vy =",
"axyaw.plot(np.matrix(t).T, np.matrix(yaw).T + 0, 'b', label='Heading') axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw,",
"row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15] *",
"axyaw.plot(t, orig_yaw, 'b--', label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd,",
"39, \"Net Force\", ax) plot_vec(data, 42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\",",
"= plt.subplot(111, sharex=ax) axwind.plot(t, true_wind_speed, 'r', label=\"True Wind Speed (m/s)\") axwind.plot(t, wind_speed, 'b',",
"plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x, label=name+\" x\") plt.plot(t, y, label=name+\" y\") plt.plot(t, z,",
"is blowing bottom-right-to-top-left on screen)--Arrows and colors represent velocities\") plt.xlabel(\"X position (deg longitude)\")",
"/ np.pi) pitchvarstart = max(-100, -len(pitch)) pitchvar.append(np.std(pitch[pitchvarstart:])) x.append(row[8]) y.append(row[9]) vx.append(row[10]) vy.append(row[11]) speed.append(np.hypot(vx[-1], vy[-1]))",
"'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t, [n *",
"\"Hull Torque\", ax) plot_vec(data, 54, \"Righting Torque\", ax) plot_vec(data, 57, \"Net Torque\", ax)",
"label='True Wind Angle') axrudder = axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm',",
"Torque\", ax) plot_vec(data, 48, \"Keel Torque\", ax) plot_vec(data, 51, \"Hull Torque\", ax) plot_vec(data,",
"heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True",
"Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind Angle') axrudder",
"'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm', label='True Wind",
"for row in data: if row[0] < 4000: continue for i in range(len(row)):",
"2 * np.pi while (theta < -np.pi): theta += 2 * np.pi return",
"#plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952], '*-', label=\"waypoints\") if",
"heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180.",
"true_alphaw.append(norm_theta(np.arctan2(row[13], row[12]))* 180. / np.pi) true_wind_speed.append(np.sqrt(row[12] ** 2 + row[13] ** 2)) heading_cmd.append(row[15]",
"label='Wind Speed (m/s)') ax2.plot(t, true_wind_speed, label='True Wind Speed (m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right')",
"#!/usr/bin/python3 import numpy as np import sys from matplotlib import pyplot as plt",
"42, \"Sail Torque\", ax) plot_vec(data, 45, \"Rudder Torque\", ax) plot_vec(data, 48, \"Keel Torque\",",
"[] orig_yaw = [] orig_heel = [] orig_speed = [] for row in",
"/ np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi) pitch.append(norm_theta(row[7]) * 180. / np.pi) pitchvarstart",
"pyplot as plt def norm_theta(theta): while (theta > np.pi): theta -= 2 *",
"y = data[:, starti+1] z = data[:, starti+2] plt.figure() plt.subplot(111, sharex=ax) plt.plot(t, x,",
"= [] wind_speed = [] true_alphaw = [] true_wind_speed = [] heading_cmd =",
"> np.pi): theta -= 2 * np.pi while (theta < -np.pi): theta +=",
"np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45]) axyaw.legend(loc='upper left') axrudder.legend(loc='upper right')",
"180. / np.pi) heel.append(norm_theta(row[6]) * 180. / np.pi) orig_heel.append(norm_theta(row[21]) * 180. / np.pi)",
"label=\"waypoints\") if False: plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position",
"1e5: row[i] = float(\"nan\") # if row[0] > 4485: # break t.append(row[0]) sail.append(row[3]",
"y, label=\"Boat Path\") #plt.plot([-76.477516, -76.475533, -76.474373, -76.477615, -76.479126], [38.98278, 38.98209, 38.98365, 38.985771, 38.983952],",
"np.pi) yaw.append(norm_theta(row[5]) * 180. / np.pi) orig_yaw.append(norm_theta(row[20]) * 180. / np.pi) heel.append(norm_theta(row[6]) *",
"bias') ax.plot(t, y - y[0], label='y less bias') ax2 = ax.twinx() ax2.plot(t, vx,",
"alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 + row[2] ** 2))",
"label='Orig Yaw') axyaw.plot(t, alphaw, 'g', label='Apparent Wind Angle') axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd')",
"[] yaw = [] heel = [] pitch = [] heading = []",
"(m/s)') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.figure() axyh = plt.subplot(111, sharex=ax) axyh.plot(t, yaw, label='Yaw')",
"longitude)\") plt.ylabel(\"Y position (deg latitude)\") plt.legend() plt.figure() ax = plt.subplot(111) ax.plot(t, x -",
"break t.append(row[0]) sail.append(row[3] * 180. / np.pi) rudder.append(row[4] * 180. / np.pi) yaw.append(norm_theta(row[5])",
"speed = [] t = [] yaw = [] heel = [] pitch",
"[n * 100 for n in pitchvar], label='Pitch Stddev * 100') axyh.legend() plt.figure()",
"axyaw.plot(t, heading_cmd, 'b-.', label='Heading Cmd') axyaw.plot(t, rudder_mode, 'r*', label='Rudder Mode') #axyaw.plot(t, true_alphaw, 'm',",
"ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36,",
"axyh.plot(t, heel, 'g', label='Heel') axyh.plot(t, orig_heel, 'g--', label='Original Heel') axyh.plot(t, pitch, label='Pitch') axyh.plot(t,",
"plt.quiver(x, y, vx, vy, np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing",
"'k', label='Boat Speed') axrudder.plot(t, np.array(orig_speed) * 10, 'k--', label='Orig Boat Speed') axrudder.set_ylim([-45, 45])",
"180. / np.pi) alphaw.append(np.arctan2(row[2], row[1]) * 180. / np.pi) wind_speed.append(np.sqrt(row[1] ** 2 +",
"np.hypot(vx, vy)) plt.colorbar(label=\"Speed (m/s)\") plt.title(\"Boat Position (Wind is blowing bottom-right-to-top-left on screen)--Arrows and",
"y = [] vx = [] vy = [] speed = [] t",
"left') axrudder.legend(loc='upper right') plt.title('Boat data while beam reaching and close hauled') axyaw.set_ylabel('Heading and",
"plt.subplot(111) ax.plot(t, x - x[0], label='x less bias') ax.plot(t, y - y[0], label='y",
"z, label=name+\" z\") # plt.ylim(-maxy, maxy) plt.legend() data = np.genfromtxt(\"sep11logsim.csv\", delimiter=',')[:, :] x",
"* np.pi return theta def plot_vec(d, starti, name, ax, maxy=50): t = data[:,",
"'c--', label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10,",
"= axyaw.twinx() axrudder.plot(t, rudder, 'r', label='Rudder') axrudder.plot(t, sail, 'm', label='Sail') axrudder.plot(t, heel, 'c',",
"label='Orig Heel'); axrudder.plot(t, leeway, 'y', label='Leeway Angle') axrudder.plot(t, np.hypot(vx, vy) * 10, 'k',",
"\"Rudder Force\", ax) plot_vec(data, 33, \"Keel Force\", ax) plot_vec(data, 36, \"Hull Force\", ax)",
"axwinddir.legend(loc='upper right') plot_vec(data, 27, \"Sail Force\", ax) plot_vec(data, 30, \"Rudder Force\", ax) plot_vec(data,",
"= [] true_wind_speed = [] heading_cmd = [] rudder_mode = [] orig_yaw ="
] |
[
"import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1);",
"coding: utf-8 -*- import wave as wv import numpy as np import matplotlib.pyplot",
"#!/usr/bin/python #-*- coding: utf-8 -*- import wave as wv import numpy as np",
"<reponame>zaqwes8811/voicegen #!/usr/bin/python #-*- coding: utf-8 -*- import wave as wv import numpy as",
"as wv import numpy as np import matplotlib.pyplot as plt x = np.arange(0,",
"import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x,",
"matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y)",
"utf-8 -*- import wave as wv import numpy as np import matplotlib.pyplot as",
"wave as wv import numpy as np import matplotlib.pyplot as plt x =",
"as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y =",
"np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x)",
"wv import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5,",
"-*- import wave as wv import numpy as np import matplotlib.pyplot as plt",
"#-*- coding: utf-8 -*- import wave as wv import numpy as np import",
"numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y",
"import wave as wv import numpy as np import matplotlib.pyplot as plt x"
] |
[
"= fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting in enumerate(newSettings): if",
"of tuples each entry in the list is a setting with its name",
"settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting",
"around formlayout \"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a class around formlayout",
"---------- setting : list of tuples each entry in the list is a",
"self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ):",
"as the first element and current value as second like for formlayout from",
"change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings != None:",
"if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self):",
"current value as second like for formlayout from fedit \"\"\" self.settingsDict = {}",
"__init__(self, settings): \"\"\" initialize the advanced settings Parameters ---------- setting : list of",
"editable settings: wrapper around formlayout \"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a",
"easy to use settings initalized with a list of tuples that specifiy the",
"it can return a dictionary with the settings to easily use in the",
"settings self.update_dict() def update_dict(self): for element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]]",
"self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings",
"newSettings = fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting in enumerate(newSettings):",
"settings: wrapper around formlayout \"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a class",
"def change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings !=",
"None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1]",
"self.settingsDict = {} self.settingsList = settings self.update_dict() def update_dict(self): for element in self.settingsList:",
"setting : list of tuples each entry in the list is a setting",
"list of tuples that specifiy the settings it can return a dictionary with",
"settings Parameters ---------- setting : list of tuples each entry in the list",
"advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings != None: for i,",
"like for formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict()",
"<reponame>mgotz/PyGUITools #!/usr/bin/env python2 # -*- coding: utf-8 -*- \"\"\" easily editable settings: wrapper",
"settings): \"\"\" initialize the advanced settings Parameters ---------- setting : list of tuples",
"in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1]",
"title=title) if newSettings != None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) ==",
"from fedit \"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict() def update_dict(self): for",
"as second like for formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList =",
"initialize the advanced settings Parameters ---------- setting : list of tuples each entry",
"the advanced settings Parameters ---------- setting : list of tuples each entry in",
"fedit class EasyEditSettings(): \"\"\"a class around formlayout to give easy to use settings",
"with a list of tuples that specifiy the settings it can return a",
"title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if newSettings != None: for",
"a list of tuples that specifiy the settings it can return a dictionary",
"around formlayout to give easy to use settings initalized with a list of",
"with its name as the first element and current value as second like",
"class around formlayout to give easy to use settings initalized with a list",
"dictionary with the settings to easily use in the application \"\"\" def __init__(self,",
"python2 # -*- coding: utf-8 -*- \"\"\" easily editable settings: wrapper around formlayout",
"for element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]]",
"class EasyEditSettings(): \"\"\"a class around formlayout to give easy to use settings initalized",
"value as second like for formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList",
"!= None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList =",
"for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0]",
"= {} self.settingsList = settings self.update_dict() def update_dict(self): for element in self.settingsList: if",
"i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] =",
"element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings =",
"of tuples that specifiy the settings it can return a dictionary with the",
"get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title)",
"tuples each entry in the list is a setting with its name as",
"entry in the list is a setting with its name as the first",
"specifiy the settings it can return a dictionary with the settings to easily",
"to easily use in the application \"\"\" def __init__(self, settings): \"\"\" initialize the",
"import fedit class EasyEditSettings(): \"\"\"a class around formlayout to give easy to use",
"the application \"\"\" def __init__(self, settings): \"\"\" initialize the advanced settings Parameters ----------",
"\"\"\" initialize the advanced settings Parameters ---------- setting : list of tuples each",
"type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return",
"\"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict() def update_dict(self): for element in",
"list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else: self.settingsList[i] =",
"tuples that specifiy the settings it can return a dictionary with the settings",
"formlayout \"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a class around formlayout to",
"for formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict() def",
"list is a setting with its name as the first element and current",
"newSettings != None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList",
"settings it can return a dictionary with the settings to easily use in",
"use in the application \"\"\" def __init__(self, settings): \"\"\" initialize the advanced settings",
"second like for formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList = settings",
"formlayout from fedit \"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict() def update_dict(self):",
"): newSettings = fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting in",
"setting with its name as the first element and current value as second",
"settings initalized with a list of tuples that specifiy the settings it can",
"def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList,",
"advanced settings Parameters ---------- setting : list of tuples each entry in the",
"utf-8 -*- \"\"\" easily editable settings: wrapper around formlayout \"\"\" from formlayout import",
"= element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings",
"\"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a class around formlayout to give",
"self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def",
"else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced settings\"",
"enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] =",
"newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting",
"that specifiy the settings it can return a dictionary with the settings to",
"list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def",
"application \"\"\" def __init__(self, settings): \"\"\" initialize the advanced settings Parameters ---------- setting",
"formlayout to give easy to use settings initalized with a list of tuples",
"with the settings to easily use in the application \"\"\" def __init__(self, settings):",
"def __init__(self, settings): \"\"\" initialize the advanced settings Parameters ---------- setting : list",
"== list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else: self.settingsList[i]",
"coding: utf-8 -*- \"\"\" easily editable settings: wrapper around formlayout \"\"\" from formlayout",
"element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] =",
"\"\"\" easily editable settings: wrapper around formlayout \"\"\" from formlayout import fedit class",
"-*- coding: utf-8 -*- \"\"\" easily editable settings: wrapper around formlayout \"\"\" from",
"the first element and current value as second like for formlayout from fedit",
"= element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit",
"in enumerate(newSettings): if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i]",
"if type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList)",
"Parameters ---------- setting : list of tuples each entry in the list is",
"name as the first element and current value as second like for formlayout",
"if newSettings != None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1]) == list:",
"type(self.settingsList[i][1]) == list: tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else:",
"def update_dict(self): for element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1]",
"return self.settingsDict def change_settings(self, title=\"Edit advanced settings\" ): newSettings = fedit(self.settingsList, title=title) if",
"and current value as second like for formlayout from fedit \"\"\" self.settingsDict =",
"to use settings initalized with a list of tuples that specifiy the settings",
"== list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict",
"the settings it can return a dictionary with the settings to easily use",
"use settings initalized with a list of tuples that specifiy the settings it",
"EasyEditSettings(): \"\"\"a class around formlayout to give easy to use settings initalized with",
"\"\"\"a class around formlayout to give easy to use settings initalized with a",
"initalized with a list of tuples that specifiy the settings it can return",
"formlayout import fedit class EasyEditSettings(): \"\"\"a class around formlayout to give easy to",
"give easy to use settings initalized with a list of tuples that specifiy",
"update_dict(self): for element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] = element[1][element[1][0]+1] else:",
"self.settingsDict[element[0]] = element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def change_settings(self,",
"its name as the first element and current value as second like for",
"the settings to easily use in the application \"\"\" def __init__(self, settings): \"\"\"",
"can return a dictionary with the settings to easily use in the application",
"fedit(self.settingsList, title=title) if newSettings != None: for i, newSetting in enumerate(newSettings): if type(self.settingsList[i][1])",
"settings to easily use in the application \"\"\" def __init__(self, settings): \"\"\" initialize",
"# -*- coding: utf-8 -*- \"\"\" easily editable settings: wrapper around formlayout \"\"\"",
"is a setting with its name as the first element and current value",
"easily use in the application \"\"\" def __init__(self, settings): \"\"\" initialize the advanced",
"element and current value as second like for formlayout from fedit \"\"\" self.settingsDict",
"self.settingsList = settings self.update_dict() def update_dict(self): for element in self.settingsList: if type(element[1]) ==",
": list of tuples each entry in the list is a setting with",
"element[1][element[1][0]+1] else: self.settingsDict[element[0]] = element[1] def get_settings(self): return self.settingsDict def change_settings(self, title=\"Edit advanced",
"= self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else: self.settingsList[i] = (self.settingsList[i][0],newSetting) self.update_dict()",
"{} self.settingsList = settings self.update_dict() def update_dict(self): for element in self.settingsList: if type(element[1])",
"the list is a setting with its name as the first element and",
"in the list is a setting with its name as the first element",
"a setting with its name as the first element and current value as",
"#!/usr/bin/env python2 # -*- coding: utf-8 -*- \"\"\" easily editable settings: wrapper around",
"wrapper around formlayout \"\"\" from formlayout import fedit class EasyEditSettings(): \"\"\"a class around",
"fedit \"\"\" self.settingsDict = {} self.settingsList = settings self.update_dict() def update_dict(self): for element",
"-*- \"\"\" easily editable settings: wrapper around formlayout \"\"\" from formlayout import fedit",
"easily editable settings: wrapper around formlayout \"\"\" from formlayout import fedit class EasyEditSettings():",
"each entry in the list is a setting with its name as the",
"= settings self.update_dict() def update_dict(self): for element in self.settingsList: if type(element[1]) == list:",
"to give easy to use settings initalized with a list of tuples that",
"tempList = self.settingsList[i][1] tempList[0] = newSetting self.settingsList[i] = (self.settingsList[i][0],tempList) else: self.settingsList[i] = (self.settingsList[i][0],newSetting)",
"list of tuples each entry in the list is a setting with its",
"return a dictionary with the settings to easily use in the application \"\"\"",
"\"\"\" def __init__(self, settings): \"\"\" initialize the advanced settings Parameters ---------- setting :",
"a dictionary with the settings to easily use in the application \"\"\" def",
"in the application \"\"\" def __init__(self, settings): \"\"\" initialize the advanced settings Parameters",
"first element and current value as second like for formlayout from fedit \"\"\"",
"self.update_dict() def update_dict(self): for element in self.settingsList: if type(element[1]) == list: self.settingsDict[element[0]] =",
"from formlayout import fedit class EasyEditSettings(): \"\"\"a class around formlayout to give easy"
] |
[
"<gh_stars>10-100 from gpiozero import Servo servoPin=17 servoCorrection=0.5 maxPW=(2.0+servoCorrection)/1000 minPW=(1.0-servoCorrection)/1000 servo=Servo(servoPin, min_pulse_width=minPW, max_pulse_width=maxPW) servo.min()"
] |
[
"call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) #",
"staticmethod and classmethod specifically (iff obj is a class) if inspect.isclass(obj): if hasattr(call,",
"''' undo the effects of wrapfunc(obj, name, processor) ''' setattr(obj, name, getattr(obj, name).original)",
"identical wrappings if avoid_doublewrap and getattr(call, 'processor', None) is processor: return # get",
"def unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj, name, processor) ''' setattr(obj,",
"future unwrapping and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor #",
"= call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name)",
"# finally, install the wrapper closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj,",
"name): ''' undo the effects of wrapfunc(obj, name, processor) ''' setattr(obj, name, getattr(obj,",
"classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper closure as requested",
"*args, **kwargs) \"\"\" # get the callable at obj.<name> call = getattr(obj, name)",
"classmethod specifically (iff obj is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if",
"install the wrapper closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): '''",
"else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper closure as requested setattr(obj,",
"call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set attributes, for future",
"for future unwrapping and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor",
"so that calling it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get",
"def wrapfunc(obj, name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it actually",
"unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj, name, processor) ''' setattr(obj, name,",
"the callable at obj.<name> call = getattr(obj, name) # optionally avoid multiple identical",
"= processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod",
"*args, **kwargs) # set attributes, for future unwrapping and to avoid double-wrapping wrappedfunc.original",
"hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally,",
"processor(original_callable, *args, **kwargs) \"\"\" # get the callable at obj.<name> call = getattr(obj,",
"call = getattr(obj, name) # optionally avoid multiple identical wrappings if avoid_doublewrap and",
"that calling it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get the",
"wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper closure as requested setattr(obj, name,",
"if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the",
"avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it actually calls, instead, processor(original_callable, *args,",
"name) # optionally avoid multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor', None)",
"class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc",
"wrapper closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args,",
"'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install",
"processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it actually calls, instead, processor(original_callable,",
"attributes, for future unwrapping and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor =",
"the wrapper closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable,",
"if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc =",
"wrappings if avoid_doublewrap and getattr(call, 'processor', None) is processor: return # get underlying",
"callable at obj.<name> call = getattr(obj, name) # optionally avoid multiple identical wrappings",
"**kwargs) # set attributes, for future unwrapping and to avoid double-wrapping wrappedfunc.original =",
"def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set attributes, for future unwrapping",
"set attributes, for future unwrapping and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor",
"setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj, name,",
"call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper",
"'processor', None) is processor: return # get underlying function (if any), and anyway",
"name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj, name, processor)",
"instead, processor(original_callable, *args, **kwargs) \"\"\" # get the callable at obj.<name> call =",
"optionally avoid multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor', None) is processor:",
"calling it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get the callable",
"and getattr(call, 'processor', None) is processor: return # get underlying function (if any),",
"return processor(original_callable, *args, **kwargs) # set attributes, for future unwrapping and to avoid",
"= getattr(obj, name) # optionally avoid multiple identical wrappings if avoid_doublewrap and getattr(call,",
"# optionally avoid multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor', None) is",
"as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects of",
"anyway def the wrapper closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs):",
"and anyway def the wrapper closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args,",
"if avoid_doublewrap and getattr(call, 'processor', None) is processor: return # get underlying function",
"processor(original_callable, *args, **kwargs) # set attributes, for future unwrapping and to avoid double-wrapping",
"2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod and classmethod specifically",
"and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor # 2.4 only:",
"(if any), and anyway def the wrapper closure original_callable = getattr(call, 'im_func', call)",
"original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) #",
"wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set attributes, for future unwrapping and",
"name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it actually calls, instead,",
"# set attributes, for future unwrapping and to avoid double-wrapping wrappedfunc.original = call",
"wrappedfunc.original = call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__',",
"wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod and classmethod specifically (iff obj",
"calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get the callable at obj.<name> call",
"getattr(obj, name) # optionally avoid multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor',",
"# 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod and classmethod",
"underlying function (if any), and anyway def the wrapper closure original_callable = getattr(call,",
"obj is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc =",
"wrapper closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the",
"unwrapping and to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor # 2.4",
"only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod and classmethod specifically (iff",
"the wrapper closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo",
"actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get the callable at obj.<name>",
"patch obj.<name> so that calling it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\"",
"= getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set",
"return # get underlying function (if any), and anyway def the wrapper closure",
"function (if any), and anyway def the wrapper closure original_callable = getattr(call, 'im_func',",
"closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs)",
"= getattr(call, '__name__', name) # rewrap staticmethod and classmethod specifically (iff obj is",
"'__name__', name) # rewrap staticmethod and classmethod specifically (iff obj is a class)",
"rewrap staticmethod and classmethod specifically (iff obj is a class) if inspect.isclass(obj): if",
"def the wrapper closure original_callable = getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return",
"at obj.<name> call = getattr(obj, name) # optionally avoid multiple identical wrappings if",
"**kwargs): return processor(original_callable, *args, **kwargs) # set attributes, for future unwrapping and to",
"None) is processor: return # get underlying function (if any), and anyway def",
"inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc)",
"a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else:",
"processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap staticmethod and",
"obj.<name> so that calling it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" #",
"getattr(call, '__name__', name) # rewrap staticmethod and classmethod specifically (iff obj is a",
"getattr(call, 'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set attributes,",
"avoid multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor', None) is processor: return",
"import inspect def wrapfunc(obj, name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling",
"finally, install the wrapper closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name):",
"and classmethod specifically (iff obj is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'):",
"(iff obj is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc",
"it actually calls, instead, processor(original_callable, *args, **kwargs) \"\"\" # get the callable at",
"to avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__",
"wrapfunc(obj, name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it actually calls,",
"wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj, name, processor) '''",
"name) # rewrap staticmethod and classmethod specifically (iff obj is a class) if",
"# get underlying function (if any), and anyway def the wrapper closure original_callable",
"**kwargs) \"\"\" # get the callable at obj.<name> call = getattr(obj, name) #",
"inspect def wrapfunc(obj, name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that calling it",
"wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper closure",
"wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ = getattr(call, '__name__', name) # rewrap",
"avoid_doublewrap and getattr(call, 'processor', None) is processor: return # get underlying function (if",
"'im_func', call) def wrappedfunc(*args, **kwargs): return processor(original_callable, *args, **kwargs) # set attributes, for",
"# get the callable at obj.<name> call = getattr(obj, name) # optionally avoid",
"= classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) # finally, install the wrapper closure as",
"# rewrap staticmethod and classmethod specifically (iff obj is a class) if inspect.isclass(obj):",
"get the callable at obj.<name> call = getattr(obj, name) # optionally avoid multiple",
"multiple identical wrappings if avoid_doublewrap and getattr(call, 'processor', None) is processor: return #",
"requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects of wrapfunc(obj,",
"= staticmethod(wrappedfunc) # finally, install the wrapper closure as requested setattr(obj, name, wrappedfunc)",
"<reponame>ch1huizong/learning import inspect def wrapfunc(obj, name, processor, avoid_doublewrap=True): \"\"\" patch obj.<name> so that",
"any), and anyway def the wrapper closure original_callable = getattr(call, 'im_func', call) def",
"get underlying function (if any), and anyway def the wrapper closure original_callable =",
"avoid double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ =",
"if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc) else: wrappedfunc = staticmethod(wrappedfunc) #",
"double-wrapping wrappedfunc.original = call wrappedfunc.processor = processor # 2.4 only: wrappedfunc.__name__ = getattr(call,",
"is processor: return # get underlying function (if any), and anyway def the",
"\"\"\" # get the callable at obj.<name> call = getattr(obj, name) # optionally",
"processor: return # get underlying function (if any), and anyway def the wrapper",
"is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self: wrappedfunc = classmethod(wrappedfunc)",
"specifically (iff obj is a class) if inspect.isclass(obj): if hasattr(call, 'im_self'): if call.im_self:",
"\"\"\" patch obj.<name> so that calling it actually calls, instead, processor(original_callable, *args, **kwargs)",
"staticmethod(wrappedfunc) # finally, install the wrapper closure as requested setattr(obj, name, wrappedfunc) def",
"obj.<name> call = getattr(obj, name) # optionally avoid multiple identical wrappings if avoid_doublewrap",
"closure as requested setattr(obj, name, wrappedfunc) def unwrapfunc(obj, name): ''' undo the effects",
"getattr(call, 'processor', None) is processor: return # get underlying function (if any), and"
] |
[
"SYM_UNK = '<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK)",
"data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name",
"load(self, location): with open(location, 'rb') as f: data = json.load(f) self.word2idx = data['word2idx']",
"= json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name,",
"(self, word): if word not in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx]",
"open(location, 'rb') as f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word']",
"or response sequences. Returns: A list of their lengths. \"\"\" max_length = inputs.size(1)",
"specified word and updates the total number of unique words. Args: word: String",
"9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch import torchtext import json class",
"in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] = word self.idx += 1",
"class Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>' # Unknown",
"embedding to use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to generate embeddings.",
"location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f)",
"f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx']",
"= data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str): Which",
"the total number of unique words. Args: word: String representation of the word.",
"self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if word not in self.word2idx:",
"GloVe embedding to use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to generate",
"json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location): with open(location, 'rb')",
"json class Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>' #",
"Created on Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch import",
"-*- coding: utf-8 -*- \"\"\" Created on Thu Apr 9 18:56:39 2020 @author:",
"'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location): with open(location, 'rb') as f:",
"of the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1",
"String representation of the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx",
"__call__(self, word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self):",
"'rb') as f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx",
"in inputs. Args: inputs: A batch of tensors containing the question or response",
"word): \"\"\"Removes a specified word and updates the total number of unique words.",
"torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # ===========================================================",
"not in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] = word self.idx +=",
"of unique words. Args: word: String representation of the word. \"\"\" if word",
"def __len__(self): return len(self.word2idx) def save(self, location): with open(location, 'w') as f: json.dump({'word2idx':",
"if word not in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] = word",
"glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates",
"Args: name (str): Which GloVe embedding to use. embed_size (int): Dimensionality of embeddings.",
"self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location): with",
"=========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the sequences in inputs.",
"self.idx2word, 'idx': self.idx}, f) def load(self, location): with open(location, 'rb') as f: data",
"return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location): with open(location, 'w') as",
"def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the sequences in inputs. Args:",
"1 def __call__(self, word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word]",
"lenght of all the sequences in inputs. Args: inputs: A batch of tensors",
"self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str):",
"Args: word: String representation of the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word)",
"self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word not in self.word2idx: self.word2idx [word]",
"embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str): Which GloVe embedding to use.",
"'<pad>' # padding. SYM_UNK = '<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={}",
"self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor.",
"sequences. Returns: A list of their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0)",
"if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx)",
"unique words. Args: word: String representation of the word. \"\"\" if word in",
"remove_word(self, word): \"\"\"Removes a specified word and updates the total number of unique",
"to use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to generate embeddings. Returns:",
"1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths = list(max_length - inputs.data.eq(pad).sum(1).squeeze()) return",
"self.idx2word [self.idx] = word self.idx += 1 def remove_word(self, word): \"\"\"Removes a specified",
"question or response sequences. Returns: A list of their lengths. \"\"\" max_length =",
"sequences in inputs. Args: inputs: A batch of tensors containing the question or",
"\"\"\" import torch import torchtext import json class Vocabulary (object): SYM_PAD = '<pad>'",
"Returns: A list of their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) ==",
"Returns: embedding (vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name,",
"= inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths",
"save(self, location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx},",
"(vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size",
"\"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word):",
"import json class Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>'",
"word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size,",
"inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths = list(max_length -",
"word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return",
"padding. SYM_UNK = '<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD)",
"of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding",
"def add_word (self, word): if word not in self.word2idx: self.word2idx [word] = self.idx",
"Dimensionality of embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor",
"lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length -",
"# Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self,",
"number of unique words. Args: word: String representation of the word. \"\"\" if",
"def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str): Which GloVe embedding",
"== 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths = list(max_length - inputs.data.eq(pad).sum(1).squeeze())",
"Tensor of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab)",
"# =========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of",
"list of their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) == 1: lengths",
"__len__(self): return len(self.word2idx) def save(self, location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx,",
"their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length",
"open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self,",
"self.idx -= 1 def __call__(self, word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK]",
"response sequences. Returns: A list of their lengths. \"\"\" max_length = inputs.size(1) if",
"add_word (self, word): if word not in self.word2idx: self.word2idx [word] = self.idx self.idx2word",
"location): with open(location, 'rb') as f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word",
"18:56:39 2020 @author: sarroutim2 \"\"\" import torch import torchtext import json class Vocabulary",
"@author: sarroutim2 \"\"\" import torch import torchtext import json class Vocabulary (object): SYM_PAD",
"self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location): with open(location, 'w')",
"word self.idx += 1 def remove_word(self, word): \"\"\"Removes a specified word and updates",
"= glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0):",
"\"\"\"Removes a specified word and updates the total number of unique words. Args:",
"= data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args:",
"=========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all",
"# Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the",
"self.idx += 1 def remove_word(self, word): \"\"\"Removes a specified word and updates the",
"if inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths = list(max_length",
"lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths = list(max_length - inputs.data.eq(pad).sum(1).squeeze()) return lengths",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Thu Apr 9",
"SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>' # Unknown word. def __init__(self):",
"vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe word",
"self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if word not in self.word2idx: return",
"pad=0): \"\"\"Calculates the lenght of all the sequences in inputs. Args: inputs: A",
"of all the sequences in inputs. Args: inputs: A batch of tensors containing",
"use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding",
"on Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch import torchtext",
"\"\"\"Construct embedding tensor. Args: name (str): Which GloVe embedding to use. embed_size (int):",
"containing the question or response sequences. Returns: A list of their lengths. \"\"\"",
"= '<pad>' # padding. SYM_UNK = '<unk>' # Unknown word. def __init__(self): self.word2idx={}",
"Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>' # Unknown word.",
"not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self,",
"embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size,",
"to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\"",
"self.word2idx [word] = self.idx self.idx2word [self.idx] = word self.idx += 1 def remove_word(self,",
"torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size):",
"self.add_word(self.SYM_UNK) def add_word (self, word): if word not in self.word2idx: self.word2idx [word] =",
"f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location): with open(location,",
"dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i]",
"embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\" glove =",
"updates the total number of unique words. Args: word: String representation of the",
"Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe word embeddings.",
"self.idx}, f) def load(self, location): with open(location, 'rb') as f: data = json.load(f)",
"word: String representation of the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx)",
"def __call__(self, word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def",
"vocab): \"\"\"Construct embedding tensor. Args: name (str): Which GloVe embedding to use. embed_size",
"words. Args: word: String representation of the word. \"\"\" if word in self.word2idx:",
"\"\"\" max_length = inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1))",
"def save(self, location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx':",
"self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location): with open(location, 'w') as f:",
"'<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word",
"def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word",
"torch import torchtext import json class Vocabulary (object): SYM_PAD = '<pad>' # padding.",
"word): if word not in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] =",
"representation of the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -=",
"embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe",
"if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if",
"[word] = self.idx self.idx2word [self.idx] = word self.idx += 1 def remove_word(self, word):",
"len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return",
"# padding. SYM_UNK = '<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0",
"len(self.word2idx) def save(self, location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word,",
"\"\"\"Calculates the lenght of all the sequences in inputs. Args: inputs: A batch",
"# =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the sequences in",
"tensor. Args: name (str): Which GloVe embedding to use. embed_size (int): Dimensionality of",
"embedding tensor. Args: name (str): Which GloVe embedding to use. embed_size (int): Dimensionality",
"of tensors containing the question or response sequences. Returns: A list of their",
"embed_size): Tensor of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size =",
"generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\" glove",
"embedding # =========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght",
"return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location): with open(location,",
"embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size)",
"# -*- coding: utf-8 -*- \"\"\" Created on Thu Apr 9 18:56:39 2020",
"word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if word",
"'idx': self.idx}, f) def load(self, location): with open(location, 'rb') as f: data =",
"self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab):",
"of their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) == 1: lengths =",
"'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location):",
"[self.idx] = word self.idx += 1 def remove_word(self, word): \"\"\"Removes a specified word",
"the word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def",
"Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch import torchtext import json",
"self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if word not in",
"as f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx =",
"import torch import torchtext import json class Vocabulary (object): SYM_PAD = '<pad>' #",
"range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. # =========================================================== def",
"get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str): Which GloVe embedding to",
"= '<unk>' # Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def",
"embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding",
"of embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size): Tensor of",
"= word self.idx += 1 def remove_word(self, word): \"\"\"Removes a specified word and",
"process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the sequences in inputs. Args: inputs:",
"return len(self.word2idx) def save(self, location): with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word':",
"2020 @author: sarroutim2 \"\"\" import torch import torchtext import json class Vocabulary (object):",
"for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers.",
"1 def remove_word(self, word): \"\"\"Removes a specified word and updates the total number",
"data = json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def",
"(str): Which GloVe embedding to use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary",
"= torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in",
"the sequences in inputs. Args: inputs: A batch of tensors containing the question",
"+= 1 def remove_word(self, word): \"\"\"Removes a specified word and updates the total",
"inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else: lengths =",
"data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding",
"utf-8 -*- \"\"\" Created on Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\"",
"(object): SYM_PAD = '<pad>' # padding. SYM_UNK = '<unk>' # Unknown word. def",
"name (str): Which GloVe embedding to use. embed_size (int): Dimensionality of embeddings. vocab:",
"and updates the total number of unique words. Args: word: String representation of",
"the question or response sequences. Returns: A list of their lengths. \"\"\" max_length",
"Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch import torchtext import",
"= len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]]",
"data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct embedding tensor. Args: name (str): Which GloVe",
"inputs. Args: inputs: A batch of tensors containing the question or response sequences.",
"self.idx self.idx2word [self.idx] = word self.idx += 1 def remove_word(self, word): \"\"\"Removes a",
"Unknown word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word):",
"= torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding #",
"\"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for",
"inputs: A batch of tensors containing the question or response sequences. Returns: A",
"as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location): with",
"-= 1 def __call__(self, word): if word not in self.word2idx: return self.word2idx[self.SYM_UNK] return",
"self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] = word self.idx += 1 def",
"= data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size, vocab): \"\"\"Construct",
"in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. # ===========================================================",
"with open(location, 'w') as f: json.dump({'word2idx': self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def",
"batch of tensors containing the question or response sequences. Returns: A list of",
"in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def save(self, location):",
"embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. # =========================================================== def process_lengths(inputs,",
"embed_size) for i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== #",
"all the sequences in inputs. Args: inputs: A batch of tensors containing the",
"word not in self.word2idx: self.word2idx [word] = self.idx self.idx2word [self.idx] = word self.idx",
"def load(self, location): with open(location, 'rb') as f: data = json.load(f) self.word2idx =",
"self.word2idx, 'idx2word': self.idx2word, 'idx': self.idx}, f) def load(self, location): with open(location, 'rb') as",
"word not in self.word2idx: return self.word2idx[self.SYM_UNK] return self.word2idx[word] def __len__(self): return len(self.word2idx) def",
"self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word not in self.word2idx:",
"total number of unique words. Args: word: String representation of the word. \"\"\"",
"tensors containing the question or response sequences. Returns: A list of their lengths.",
"embedding (vocab_size, embed_size): Tensor of GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size))",
"word. \"\"\" if word in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self,",
"import torchtext import json class Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK",
"word and updates the total number of unique words. Args: word: String representation",
"(int): Dimensionality of embeddings. vocab: Vocabulary to generate embeddings. Returns: embedding (vocab_size, embed_size):",
"coding: utf-8 -*- \"\"\" Created on Thu Apr 9 18:56:39 2020 @author: sarroutim2",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Thu Apr 9 18:56:39",
"-*- \"\"\" Created on Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import",
"GloVe word embeddings. \"\"\" glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding =",
"A batch of tensors containing the question or response sequences. Returns: A list",
"sarroutim2 \"\"\" import torch import torchtext import json class Vocabulary (object): SYM_PAD =",
"A list of their lengths. \"\"\" max_length = inputs.size(1) if inputs.size(0) == 1:",
"the lenght of all the sequences in inputs. Args: inputs: A batch of",
"def remove_word(self, word): \"\"\"Removes a specified word and updates the total number of",
"max_length = inputs.size(1) if inputs.size(0) == 1: lengths = list(max_length - inputs.data.eq(pad).sum(1)) else:",
"json.load(f) self.word2idx = data['word2idx'] self.idx2word = data['idx2word'] self.idx = data['idx'] def get_glove_embedding(name, embed_size,",
"__init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word not",
"i in range(vocab_size): embedding[i] = glove[vocab.idx2word[str(i)]] return embedding # =========================================================== # Helpers. #",
"<filename>utils/utils.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Thu Apr",
"glove = torchtext.vocab.GloVe(name=name, dim=str(embed_size)) vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i",
"torchtext import json class Vocabulary (object): SYM_PAD = '<pad>' # padding. SYM_UNK =",
"f) def load(self, location): with open(location, 'rb') as f: data = json.load(f) self.word2idx",
"self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word not in",
"word. def __init__(self): self.word2idx={} self.idx2word={} self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if",
"self.idx=0 self.add_word(self.SYM_PAD) self.add_word(self.SYM_UNK) def add_word (self, word): if word not in self.word2idx: self.word2idx",
"with open(location, 'rb') as f: data = json.load(f) self.word2idx = data['word2idx'] self.idx2word =",
"Args: inputs: A batch of tensors containing the question or response sequences. Returns:",
"in self.word2idx: self.word2idx.pop(word) self.idx2word.pop(self.idx) self.idx -= 1 def __call__(self, word): if word not",
"Which GloVe embedding to use. embed_size (int): Dimensionality of embeddings. vocab: Vocabulary to",
"Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the lenght of all the sequences",
"\"\"\" Created on Thu Apr 9 18:56:39 2020 @author: sarroutim2 \"\"\" import torch",
"= self.idx self.idx2word [self.idx] = word self.idx += 1 def remove_word(self, word): \"\"\"Removes",
"a specified word and updates the total number of unique words. Args: word:",
"return embedding # =========================================================== # Helpers. # =========================================================== def process_lengths(inputs, pad=0): \"\"\"Calculates the",
"vocab_size = len(vocab) embedding = torch.zeros(vocab_size, embed_size) for i in range(vocab_size): embedding[i] ="
] |
[
"from app.models.db import Db environment = os.getenv('config_name') app = create_app(environment) #creates database tables",
"from app.app import create_app from app.models.db import Db environment = os.getenv('config_name') app =",
"environment = os.getenv('config_name') app = create_app(environment) #creates database tables if they don't exist",
"app.models.db import Db environment = os.getenv('config_name') app = create_app(environment) #creates database tables if",
"create_app(environment) #creates database tables if they don't exist Db.create_tables() if __name__ == '__main__':",
"app.app import create_app from app.models.db import Db environment = os.getenv('config_name') app = create_app(environment)",
"create_app from app.models.db import Db environment = os.getenv('config_name') app = create_app(environment) #creates database",
"app = create_app(environment) #creates database tables if they don't exist Db.create_tables() if __name__",
"import Db environment = os.getenv('config_name') app = create_app(environment) #creates database tables if they",
"Db environment = os.getenv('config_name') app = create_app(environment) #creates database tables if they don't",
"import create_app from app.models.db import Db environment = os.getenv('config_name') app = create_app(environment) #creates",
"os from app.app import create_app from app.models.db import Db environment = os.getenv('config_name') app",
"<gh_stars>0 import os from app.app import create_app from app.models.db import Db environment =",
"import os from app.app import create_app from app.models.db import Db environment = os.getenv('config_name')",
"= os.getenv('config_name') app = create_app(environment) #creates database tables if they don't exist Db.create_tables()",
"os.getenv('config_name') app = create_app(environment) #creates database tables if they don't exist Db.create_tables() if",
"= create_app(environment) #creates database tables if they don't exist Db.create_tables() if __name__ ==",
"#creates database tables if they don't exist Db.create_tables() if __name__ == '__main__': app.run()"
] |
[
"prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left",
"%s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump':",
"json import sqlalchemy as sa from .dump import Dump from .restore import Restore",
"or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for",
"restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\")",
"caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\")",
"),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump",
"engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir,",
"data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if",
"from .restore import Restore from . import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python",
"with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password",
"raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI",
"logger.info('RI checks where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg) pw.change() else:",
"cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits",
"fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info('",
"else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug",
"db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.')",
"checks where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg) pw.change() else: argparse.error(\"Invalid",
"or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of",
"from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info('",
"in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug",
"logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user :",
"parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta",
"port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name']",
"if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or",
"import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation",
"\"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with",
"cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache,",
"help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\")",
"(dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching",
"logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server'])",
"import json import sqlalchemy as sa from .dump import Dump from .restore import",
"argparse import logging import json import sqlalchemy as sa from .dump import Dump",
"dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']:",
"import Dump from .restore import Restore from . import Password if __name__ ==",
"albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or",
"'__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration",
"sqlalchemy as sa from .dump import Dump from .restore import Restore from .",
"meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG",
"server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'],",
"%(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r')",
"args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration",
": %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port'])",
"for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO,",
"parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if",
"of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None,",
"for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target",
"cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else:",
"Restore from . import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'),",
"operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run",
"cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user",
"if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore finished') elif args.mode=='chg-password':",
"cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run()",
"parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in",
"logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'],",
"args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info('",
"logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port",
"help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug",
"logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" )",
"restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database",
"%d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy",
"if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw))",
": %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw,",
"pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine,",
"parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore",
"import logging import json import sqlalchemy as sa from .dump import Dump from",
"cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file",
"enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore",
"%s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'],",
"cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server'])",
"database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig(",
"open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database",
"logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file)",
"level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel(",
"format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR",
"logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine",
"dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore')",
"password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db :",
"of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args()",
"args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger()",
"Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks",
"-m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump",
"cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'],",
"parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for",
"logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db",
"not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False)",
".dump import Dump from .restore import Restore from . import Password if __name__",
"else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from",
"Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump",
"if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO",
"logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format(",
"enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file,",
"engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration",
"if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if",
"cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg)",
"as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:')",
"finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine)",
"else: logger.info('RI checks where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg) pw.change()",
"args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise",
"if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read",
"logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else",
"%s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info('",
"operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow",
"logger.info('Dump finished') elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check']",
"configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info('",
"restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg)",
"Dump from .restore import Restore from . import Password if __name__ == '__main__':",
"args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore': if not",
"as sa from .dump import Dump from .restore import Restore from . import",
"debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else",
"elif args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run()",
"%s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password:",
"restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore finished')",
"import Restore from . import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\")",
".restore import Restore from . import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m",
"left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg) pw.change() else: argparse.error(\"Invalid program mode\")",
"== '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json',",
"logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh)",
". import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of",
"import sqlalchemy as sa from .dump import Dump from .restore import Restore from",
") logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as",
"directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else",
": %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True) logger.info('SQLAlchemy engine created.') if",
"if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR )",
"mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s:",
"created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif args.mode=='restore':",
"import argparse import logging import json import sqlalchemy as sa from .dump import",
"from . import Password if __name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode",
"args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if",
"backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\"",
"configuration from %s',args.cfg_file) if args.mode!='chg-password': p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user'])",
"user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port :",
"if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check:",
"file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where",
": %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name']) engine=sa.create_engine('mssql+pyodbc://{}:{}@{}:{}/{}?driver=FreeTDS&odbc_options=\"TDS_Version=8.0\"'.format( cfg['db_user'], pw, cfg['db_server'], cfg['db_port'], cfg['db_name'] ),deprecate_large_types=True)",
"dump or restore operation\") parser.add_argument('--meta-cache',default=None, help=\"Allow caching of database meta data\") parser.add_argument('--backup-dir',default='backup',help=\"Target directory",
") logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if",
"p=Password(args.cfg_file,cfg) pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server",
"logging import json import sqlalchemy as sa from .dump import Dump from .restore",
"where left off') logger.info('Restore finished') elif args.mode=='chg-password': pw=Password(args.cfg_file, cfg) pw.change() else: argparse.error(\"Invalid program",
"sa from .dump import Dump from .restore import Restore from . import Password",
"pw=p.password logger.info('Database configuration:') logger.info(' user : %s',cfg['db_user']) logger.info(' password: %s','*'*len(pw)) logger.info(' server :",
"args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format=\"%(asctime)s:%(name)-20s:%(levelname)-7s:%(message)s\" if args.debug else \"%(asctime)s: %(message)s\"",
"%s','*'*len(pw)) logger.info(' server : %s',cfg['db_server']) logger.info(' port : %d',cfg['db_port']) logger.info(' db : %s',cfg['db_name'])",
"<gh_stars>0 import argparse import logging import json import sqlalchemy as sa from .dump",
"parser.add_argument('--backup-dir',default='backup',help=\"Target directory for backups\") parser.add_argument('--debug','-d',action=\"store_true\",default=False,help=\"Run in debug mode\") args=parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug",
"restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off') logger.info('Restore finished') elif",
"engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished') elif",
"help=\"mode of operation (dump or restore,chg-password)\") parser.add_argument('--cfg','-c',dest='cfg_file',default='albackup.json', help=\"Configuration for dump or restore operation\")",
"args.mode=='restore': if not cfg['allow_restore']: raise Exception('Configuration file prohibits restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if",
"else \"%(asctime)s: %(message)s\" ) logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None",
"__name__ == '__main__': parser=argparse.ArgumentParser(\"python -m albackup\") parser.add_argument('mode',metavar='MODE',choices=('dump','restore','chg-password'), help=\"mode of operation (dump or restore,chg-password)\")",
"logger.info('SQLAlchemy engine created.') if args.mode=='dump': dump=Dump(args.backup_dir, args.meta_cache, engine, cfg['db_name'], cfg['db_server']) dump.run() logger.info('Dump finished')",
"restore') enable_ri_check=cfg['enable_ri_check'] restore=Restore(args.backup_dir,engine) restore.run() if enable_ri_check: restore.changeRIChecks(off=False) else: logger.info('RI checks where left off')",
"logging.getLogger('sqlalchemy.engine').setLevel( logging.INFO if args.debug else logging.ERROR ) logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh:",
"from .dump import Dump from .restore import Restore from . import Password if",
"logger=logging.getLogger() cfg=None with open(args.cfg_file,'r') as fh: cfg=json.load(fh) logger.info('Read configuration from %s',args.cfg_file) if args.mode!='chg-password':"
] |
[
"Please \"\\ \"tell me about some movies you've watched first.\", \"It's gonna be",
"which movie you're talking about.\", \"To help me understand, please put quotation marks",
"reading your sentence because of the \"\\ \"quotation marks. Can you please try",
"\"\\ \"I think you'll like my recommendations.\", \"Glad you liked the movie.\", \"Sounds",
"it that was a good movie.\", \"Nice, sounds like that movie was right",
"response2 = random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses = [ \"",
"tastes align with {match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses =",
"about some movies you've watched first.\", \"It's gonna be hard for me to",
"that wasn't the movie for you.\", \"Okay you didn't like that one.\", \"Yeah",
"like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I couldn't",
"I haven't heard of that movie.\", \"Hmm I haven't heard of that movie.\",",
"one.\", \"Good, glad you enjoyed it.\", \"Okay, got it, I think I have",
"for you then. I'll keep that in mind.\", \"Okay so you did not",
"alley.\", f\"Okay so your tastes align with {match}, got it.\" ] return random.choice(responses)",
"+ response2 def utils_disliked(): responses1 = [ \"Okay got it you didn't like",
"if you liked that movie or not.\", \"Wait.. did you like or dislike",
"movie?\", \"I think I need some more information to tell whether you \"\\",
"the movie for you.\", \"Okay you didn't like that one.\", \"Yeah I've heard",
"good recommendation yet. Please \"\\ \"tell me about some movies you've watched first.\",",
"you liked it.\" ] responses2 = [ \" Now feel free to tell",
"hard for me to understand with your quotation marks.\", \"Oops, seems like your",
"\"Okay you didn't like that one.\", \"Yeah I've heard other people didn't like",
"it.\", \"Okay, got it, I think I have some other ones that you'll",
"you've seen?\", \" Any more movie opinions I should know?\", \" Anything else",
"you like or dislike that movie?\", \"I think I need some more information",
"wasn't your cup of tea.\", f\"So you did not like {match}. Got it.\",",
"I'll keep that in mind.\", \"Okay so you did not like that one.\",",
"liked {match}.\", f\"Sounds like {match} was right up your alley.\", f\"Okay so your",
"more movies or say \"\\ \"'Recommendations please!' to hear my recommendations.\", \" Any",
"don't think your quotation marks are correct. \", \"It's hard for me to",
"you.\", \"Okay you didn't like that one.\", \"Yeah I've heard other people didn't",
"def utils_liked(): responses1 = [ \"Great, glad you liked that one.\", \"Okay got",
"haven't seen that movie before, so it'll \"\\ \"be hard to recommend you",
"I'll be able to give you some great recommendations\" ] return random.choice(responses) def",
"movie title.\", \"I'm having trouble reading your sentence because of the \"\\ \"quotation",
"understand with your quotation marks.\", \"Oops, seems like your quotation marks aren't quite",
"\\ \"movie for you.\", f\"Okay got it {match} wasn't your cup of tea.\",",
"it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay so {match} was the movie",
"got it that was a good movie.\", \"Nice, sounds like that movie was",
"movies or say \"\\ \"'Recommendations please!' to hear my recommendations.\", \" Any more",
"{match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds",
"some movies you've watched first.\", \"It's gonna be hard for me to give",
"you didn't like that one.\", \"Yeah I've heard other people didn't like that",
"you'll like my recommendations.\", \"Glad you liked the movie.\", \"Sounds like you enjoyed",
"a good recommendation.\", \"I can't give a good recommendation yet. Please \"\\ \"tell",
"like that one.\", \"Yeah I've heard other people didn't like that one as",
"movie based on that one.\" ] return random.choice(responses) def utils_liked(): responses1 = [",
"or dislike that movie?\", \"I think I need some more information to tell",
"put quotation marks around the \" \\ \"movie like this \\\"The Wizard of",
"me about some movies you've watched?\", \"Please tell me about some movies you",
"liked that one.\", \"Okay got it that was a good movie.\", \"Nice, sounds",
"movies have you seen?\", \" Any other movies you've seen?\", \" Got any",
"\"Sorry, I need your opinion on a movie \"\\ \"before I can give",
"don't know anything about your tastes.\", \"I don't think I'm ready to give",
"up your alley.\", f\"Okay so your tastes align with {match}, got it.\" ]",
"you didn't like {match}.\", f\"Okay so {match} was the movie you didn't like.\",",
"heard of that movie before! Unfortunately \"\\ \"that means \\nI can't give you",
"because of the \"\\ \"quotation marks. Can you please try again? \", ]",
"or say \"\\ \"'Recommendations please!' to hear my recommendations.\", \" Any more movies",
"I give my recommendations?\" ] response1 = random.choice(responses1) response2 = '' if random.uniform(0,",
"] return random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems like you messed",
"\"Hang on, I couldn't tell if you liked that movie or not.\" ]",
"\"\\ \"recommendations if I don't know anything about your tastes.\", \"I don't think",
"\" Any other movies you've seen?\", \" Got any more hot takes?\", \"",
"some movies you've watched?\", \"Please tell me about some movies you watched first.",
"{match} was a good fit for you.\", f\"Okay got it you liked {match}.\",",
"trouble reading your sentence because of the \"\\ \"quotation marks. Can you please",
"did you like or dislike that movie?\", \"I think I need some more",
"you messed up your quotation marks. \" \\ \"Try again.\", \"Uh oh, I",
"1) < 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses",
"your cup of tea.\", f\"So you did not like {match}. Got it.\", f\"Gotcha",
"recommendations based \"\\ \"on that one.\", \"That movie is actually unfamiliar to me.\",",
"me some great feedback.\", \" What other movies have you seen?\", \" Any",
"so {match} was a good fit for you.\", f\"Okay got it you liked",
"a good fit for you.\", f\"Okay got it you liked {match}.\", f\"Sounds like",
"I need some more information to tell whether you \"\\ \"liked that movie",
"\"\\ \"before I can give you quality recommendations.\", \"Sorry, I don't have enough",
"around the \" \\ \"movie like this \\\"The Wizard of Oz\\\"\", \"It's hard",
"got it, I think I have some other ones that you'll like as",
"some more movies or say \"\\ \"'Recommendations please!' to hear my recommendations. \",",
"\"That really wasn't your movie huh.\", \"That movie wasn't for you then. I'll",
"didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I",
"[ \"Okay got it you didn't like that one.\", \"Gotcha so that wasn't",
"me before I give my recommendations?\" ] response1 = random.choice(responses1) response2 = ''",
"random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds like {match} wasn't the \"",
"I don't know anything about your tastes.\", \"I don't think I'm ready to",
"\\\"The Wizard of Oz\\\"\", \"It's hard for me to understand with your quotation",
"like that one.\", ] responses2 = [ \" Now feel free to tell",
"Got any more hot takes?\", \" Any more movie opinions I should know?\",",
"haven't heard of that movie.\", \"Hmm I haven't heard of that movie.\", \"Wow",
"you want to tell me before I give my recommendations?\" ] response1 =",
"[ \"Hmm seems like you messed up your quotation marks. \" \\ \"Try",
"one.\", \"That movie is actually unfamiliar to me.\", \"To be honest, I haven't",
"more opinions on movies you've seen?\", \" Any more movie opinions I should",
"about some movies you've watched?\", \"Please tell me about some movies you watched",
"one.\", ] responses2 = [ \" Now feel free to tell me about",
"= [ \"Great, glad you liked that one.\", \"Okay got it that was",
"\" Now feel free to tell me about some more movies or say",
"watched?\", \"Please tell me about some movies you watched first. \"\\ \"Then I'll",
"you didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry,",
"{match}.\", f\"Sounds like {match} was right up your alley.\", f\"Okay so your tastes",
"your quotation marks are correct. \", \"It's hard for me to understand which",
"ready to give a recommendation yet. \"\\ \"How about you tell me about",
"not.\", \"Wait.. did you like or dislike that movie?\", \"I think I need",
"] return random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad you liked that",
"\"\\ \"be hard to recommend you a movie based on that one.\" ]",
"like those kinds of movies. \"\\ \"I think you'll like my recommendations.\", \"Glad",
"more movies or say \"\\ \"'Recommendations please!' to hear my recommendations. \", \"",
"marks aren't quite right.\", \"Please re-check your quotation marks. There should be two",
"Any other movies you've seen?\", \" Got any more hot takes?\", \" Any",
"you then. I'll keep that in mind.\", \"Okay so you did not like",
"you liked that movie or not.\", \"Wait.. did you like or dislike that",
"to me.\", \"To be honest, I haven't seen that movie before, so it'll",
"Oz\\\"\", \"It's hard for me to understand with your quotation marks.\", \"Oops, seems",
"\"Sorry, I don't have enough information yet \"\\ \"to make a good recommendation.\",",
"response1 = random.choice(responses1) response2 = '' if random.uniform(0, 1) < 0.3: response2 =",
"me about some movies you watched first. \"\\ \"Then I'll be able to",
"\" Got any more hot takes?\", \" Any more movie opinions I should",
"tell me before I give my recommendations?\" ] response1 = random.choice(responses1) response2 =",
"you liked the movie.\", \"Sounds like you enjoyed that one.\", \"Good, glad you",
"that movie or not.\", \"Hang on, I couldn't tell if you liked that",
"never heard of that movie before! Unfortunately \"\\ \"that means \\nI can't give",
"\", \" Any more movie opinions I should know?\", \" Anything else you",
"if you liked that \" \\ \"movie or not.\", \"Sorry I'm not sure",
"not like {match}. Got it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay so",
"any more hot takes?\", \" Any more movie opinions I should know?\", \"",
"give you some great recommendations\" ] return random.choice(responses) def utils_quotations(): responses = [",
"can't quite tell what you think about that movie.\", \"I'm not quite sure",
"about some movies you watched first. \"\\ \"Then I'll be able to give",
"me to understand which movie you're talking about.\", \"To help me understand, please",
"\" What other movies have you seen?\", \" Any other movies you've seen?\",",
"\"Try again.\", \"Uh oh, I don't think your quotation marks are correct. \",",
"movie.\", \"Wow that movie is new to me. I don't know much about",
"that one.\", \"Okay got it that was a good movie.\", \"Nice, sounds like",
"\"movie for you.\", f\"Okay got it {match} wasn't your cup of tea.\", f\"So",
"Wizard of Oz\\\"\", \"It's hard for me to understand with your quotation marks.\",",
"that one.\", \"Good, glad you enjoyed it.\", \"Okay, got it, I think I",
"for you.\", f\"Okay got it {match} wasn't your cup of tea.\", f\"So you",
"marks. \" \\ \"Try again.\", \"Uh oh, I don't think your quotation marks",
"recommend you a movie based on that one.\" ] return random.choice(responses) def utils_liked():",
"def utils_low_confidence(): responses = [ \"Sorry, I couldn't tell if you liked that",
"marks.\", \"Oops, seems like your quotation marks aren't quite right.\", \"Please re-check your",
"= random.choice(responses1) response2 = '' if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2)",
"so it'll \"\\ \"be hard to recommend you a movie based on that",
"you're talking about.\", \"To help me understand, please put quotation marks around the",
"\", \" Any more movies you've seen? \", \" You're giving me some",
"random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I couldn't tell if you liked",
"you've watched?\", \"Please tell me about some movies you watched first. \"\\ \"Then",
"seen that movie before, so it'll \"\\ \"be hard to recommend you a",
"movie huh.\", \"That movie wasn't for you then. I'll keep that in mind.\",",
"tell me before I give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses",
"the \" \\ \"movie for you.\", f\"Okay got it {match} wasn't your cup",
"\"Sorry I'm not sure if you liked that one.\", \"I can't quite tell",
"to recommend you a movie based on that one.\" ] return random.choice(responses) def",
"you watched first. \"\\ \"Then I'll be able to give you some great",
"hear my recommendations.\", \" Any more movies you've seen? \", \" You're giving",
"quotation marks.\", \"Oops, seems like your quotation marks aren't quite right.\", \"Please re-check",
"align with {match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses = [",
"\"to make a good recommendation.\", \"I can't give a good recommendation yet. Please",
"type of movie.\", f\"Gotcha so {match} was a good fit for you.\", f\"Okay",
"\", \" You're giving me some great feedback.\", \" What other movies have",
"you did not like that one.\", ] responses2 = [ \" Now feel",
"f\"Okay sounds like {match} wasn't the \" \\ \"movie for you.\", f\"Okay got",
"else you want to tell me before I give my recommendations?\" ] return",
"you liked that one.\", \"I can't quite tell what you think about that",
"me before I give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses =",
"f\"Gotcha so {match} was a good fit for you.\", f\"Okay got it you",
"it, I think I have some other ones that you'll like as well.\",",
"say \"\\ \"'Recommendations please!' to hear my recommendations.\", \" Any more movies you've",
"first.\", \"It's gonna be hard for me to give you some good \"\\",
"for me to understand which movie you're talking about.\", \"To help me understand,",
"know?\", \" Anything else you want to tell me before I give my",
"liked it.\" ] responses2 = [ \" Now feel free to tell me",
"f\"Gotcha so you didn't like {match}.\", f\"Okay so {match} was the movie you",
"quotation marks. \" \\ \"Try again.\", \"Uh oh, I don't think your quotation",
"you enjoyed that one.\", \"Good, glad you enjoyed it.\", \"Okay, got it, I",
"some good recommendations based \"\\ \"on that one.\", \"That movie is actually unfamiliar",
"you then.\", f\"Got it you didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence():",
"correct. \", \"It's hard for me to understand which movie you're talking about.\",",
"movie was right up your alley.\" \"Wow so you like those kinds of",
"like or dislike that movie?\", \"I think I need some more information to",
"to tell whether you \"\\ \"liked that movie or not.\", \"Hang on, I",
"for you then.\", f\"Got it you didn't like {match}.\" ] return random.choice(responses) def",
"give you some good recommendations based \"\\ \"on that one.\", \"That movie is",
"seen? \", \" Any more movie opinions I should know?\", \" Anything else",
"you think about that movie.\", \"I'm not quite sure if you liked that",
"it.\", \"I've actually never heard of that movie before! Unfortunately \"\\ \"that means",
"return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds like {match} wasn't the",
"random def utils_min_required(): responses = [ \"Sorry, I need your opinion on a",
"yet. Please \"\\ \"tell me about some movies you've watched first.\", \"It's gonna",
"having trouble reading your sentence because of the \"\\ \"quotation marks. Can you",
"a recommendation yet. \"\\ \"How about you tell me about some movies you've",
"haven't heard of that movie.\", \"Wow that movie is new to me. I",
"liked the movie.\", \"Sounds like you enjoyed that one.\", \"Good, glad you enjoyed",
"recommendations.\", \"Sorry, I don't have enough information yet \"\\ \"to make a good",
"responses = [ \"Interesting, I haven't heard of that movie.\", \"Hmm I haven't",
"that movie.\", \"Hmm I haven't heard of that movie.\", \"Wow that movie is",
"movie before! Unfortunately \"\\ \"that means \\nI can't give you some good recommendations",
"\"Sounds like you enjoyed that one.\", \"Good, glad you enjoyed it.\", \"Okay, got",
"\" Any more movie opinions I should know?\", \" Anything else you want",
"random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_disliked():",
"< 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_disliked(): responses1 =",
"not.\", \"Sorry I'm not sure if you liked that one.\", \"I can't quite",
"\" \\ \"Try again.\", \"Uh oh, I don't think your quotation marks are",
"the \"\\ \"quotation marks. Can you please try again? \", ] return random.choice(responses)",
"feel free to tell me about some more movies or say \"\\ \"'Recommendations",
"fit for you.\", f\"Okay got it you liked {match}.\", f\"Sounds like {match} was",
"the movie for you then.\", f\"Got it you didn't like {match}.\" ] return",
"new to me. I don't know much about it.\", \"I've actually never heard",
"'' if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1 + response2",
"me to understand with your quotation marks.\", \"Oops, seems like your quotation marks",
"on, I couldn't tell if you liked that movie or not.\" ] return",
"title.\", \"I'm having trouble reading your sentence because of the \"\\ \"quotation marks.",
"it.\", \"That really wasn't your movie huh.\", \"That movie wasn't for you then.",
"you seen?\", \" Any other movies you've seen?\", \" Got any more hot",
"You're giving me some great feedback.\", \" What other movies have you seen?",
"Any other movies you've seen?\", \" Got any more opinions on movies you've",
"me about some movies you've watched first.\", \"It's gonna be hard for me",
"well.\", \"Awesome, glad you liked it.\" ] responses2 = [ \" Now feel",
"the movie.\", \"Sounds like you enjoyed that one.\", \"Good, glad you enjoyed it.\",",
"some great recommendations\" ] return random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems",
"got it {match} wasn't your cup of tea.\", f\"So you did not like",
"give you some good \"\\ \"recommendations if I don't know anything about your",
"the \" \\ \"movie like this \\\"The Wizard of Oz\\\"\", \"It's hard for",
"return random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems like you messed up",
"opinions I should know?\", \" Anything else you want to tell me before",
"you seen? \", \" Any other movies you've seen? \", \" Any more",
"like {match}.\", f\"Okay so {match} was the movie you didn't like.\", f\"{match} wasn't",
"you some great recommendations\" ] return random.choice(responses) def utils_quotations(): responses = [ \"Hmm",
"that in mind.\", \"Okay so you did not like that one.\", ] responses2",
"huh.\", \"That movie wasn't for you then. I'll keep that in mind.\", \"Okay",
"then. I'll keep that in mind.\", \"Okay so you did not like that",
"\"liked that movie or not.\", \"Hang on, I couldn't tell if you liked",
"to hear my recommendations. \", \" Any more movies you've seen? \", \"",
"\"\\ \"to make a good recommendation.\", \"I can't give a good recommendation yet.",
"< 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses =",
"of movie.\", f\"Gotcha so {match} was a good fit for you.\", f\"Okay got",
"you didn't like.\", f\"{match} wasn't the movie for you then.\", f\"Got it you",
"didn't like that one got it.\", \"That really wasn't your movie huh.\", \"That",
"up your alley.\" \"Wow so you like those kinds of movies. \"\\ \"I",
"you liked that \" \\ \"movie or not.\", \"Sorry I'm not sure if",
"\"Great, glad you liked that one.\", \"Okay got it that was a good",
"\"Then I'll be able to give you some great recommendations\" ] return random.choice(responses)",
"please put quotation marks around the \" \\ \"movie like this \\\"The Wizard",
"[ f\"Got it! So you liked {match}.\", f\"Okay so {match} was your type",
"was right up your alley.\", f\"Okay so your tastes align with {match}, got",
"def utils_quotations(): responses = [ \"Hmm seems like you messed up your quotation",
"right up your alley.\", f\"Okay so your tastes align with {match}, got it.\"",
"heard other people didn't like that one as well.\", \"So you didn't like",
"hard to recommend you a movie based on that one.\" ] return random.choice(responses)",
"please!' to hear my recommendations. \", \" Any more movies you've seen? \",",
"\" \\ \"movie like this \\\"The Wizard of Oz\\\"\", \"It's hard for me",
"some great feedback.\", \" What other movies have you seen? \", \" Any",
"return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I haven't heard of that",
"responses = [ f\"Okay sounds like {match} wasn't the \" \\ \"movie for",
"talking about.\", \"To help me understand, please put quotation marks around the \"",
"\"Oops, seems like your quotation marks aren't quite right.\", \"Please re-check your quotation",
"kinds of movies. \"\\ \"I think you'll like my recommendations.\", \"Glad you liked",
"random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it! So you liked {match}.\", f\"Okay",
"] responses2 = [ \" Now feel free to tell me about some",
"on movies you've seen?\", \" Any more movie opinions I should know?\", \"",
"other movies you've seen?\", \" Got any more hot takes?\", \" Any more",
"like you messed up your quotation marks. \" \\ \"Try again.\", \"Uh oh,",
"f\"Okay got it {match} wasn't your cup of tea.\", f\"So you did not",
"think I have some other ones that you'll like as well.\", \"Awesome, glad",
"wasn't the movie for you.\", \"Okay you didn't like that one.\", \"Yeah I've",
"seen?\", \" Any other movies you've seen?\", \" Got any more opinions on",
"please try again? \", ] return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting,",
"Unfortunately \"\\ \"that means \\nI can't give you some good recommendations based \"\\",
"you've watched first.\", \"It's gonna be hard for me to give you some",
"need some more information to tell whether you \"\\ \"liked that movie or",
"I don't have enough information yet \"\\ \"to make a good recommendation.\", \"I",
"good recommendation.\", \"I can't give a good recommendation yet. Please \"\\ \"tell me",
"wasn't for you then. I'll keep that in mind.\", \"Okay so you did",
"other movies you've seen?\", \" Got any more opinions on movies you've seen?\",",
"sure if you liked that movie or not.\", \"Wait.. did you like or",
"\", \"It's hard for me to understand which movie you're talking about.\", \"To",
"before, so it'll \"\\ \"be hard to recommend you a movie based on",
"movies have you seen? \", \" Any other movies you've seen? \", \"",
"not sure if you liked that one.\", \"I can't quite tell what you",
"one.\", \"Gotcha so that wasn't the movie for you.\", \"Okay you didn't like",
"you've seen?\", \" Got any more hot takes?\", \" Any more movie opinions",
"you've seen? \", \" Any more movie opinions I should know?\", \" Anything",
"= [ \"Sorry, I need your opinion on a movie \"\\ \"before I",
"\\nI can't give you some good recommendations based \"\\ \"on that one.\", \"That",
"it.\" ] responses2 = [ \" Now feel free to tell me about",
"dislike that movie?\", \"I think I need some more information to tell whether",
"liked that one.\", \"I can't quite tell what you think about that movie.\",",
"\"in your response surrounding the movie title.\", \"I'm having trouble reading your sentence",
"Any more movies you've seen? \", \" You're giving me some great feedback.\",",
"movie.\", \"Hmm I haven't heard of that movie.\", \"Wow that movie is new",
"two \"\\ \"in your response surrounding the movie title.\", \"I'm having trouble reading",
"\"tell me about some movies you've watched first.\", \"It's gonna be hard for",
"movies you've watched first.\", \"It's gonna be hard for me to give you",
"me.\", \"To be honest, I haven't seen that movie before, so it'll \"\\",
"like.\", f\"{match} wasn't the movie for you then.\", f\"Got it you didn't like",
"that one.\", \"Yeah I've heard other people didn't like that one as well.\",",
"you please try again? \", ] return random.choice(responses) def utils_new_movie(): responses = [",
"information yet \"\\ \"to make a good recommendation.\", \"I can't give a good",
"understand which movie you're talking about.\", \"To help me understand, please put quotation",
"some great feedback.\", \" What other movies have you seen?\", \" Any other",
"you \"\\ \"liked that movie or not.\", \"Hang on, I couldn't tell if",
"glad you liked it.\" ] responses2 = [ \" Now feel free to",
"if I don't know anything about your tastes.\", \"I don't think I'm ready",
"know much about it.\", \"I've actually never heard of that movie before! Unfortunately",
"recommendation yet. \"\\ \"How about you tell me about some movies you've watched?\",",
"more information to tell whether you \"\\ \"liked that movie or not.\", \"Hang",
"about some more movies or say \"\\ \"'Recommendations please!' to hear my recommendations.\",",
"you didn't like that one got it.\", \"That really wasn't your movie huh.\",",
"f\"Okay so {match} was the movie you didn't like.\", f\"{match} wasn't the movie",
"a good recommendation yet. Please \"\\ \"tell me about some movies you've watched",
"\"recommendations if I don't know anything about your tastes.\", \"I don't think I'm",
"of movies. \"\\ \"I think you'll like my recommendations.\", \"Glad you liked the",
"want to tell me before I give my recommendations?\" ] response1 = random.choice(responses1)",
"to tell me before I give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match):",
"wasn't the \" \\ \"movie for you.\", f\"Okay got it {match} wasn't your",
"to me. I don't know much about it.\", \"I've actually never heard of",
"me about some more movies or say \"\\ \"'Recommendations please!' to hear my",
"to give a recommendation yet. \"\\ \"How about you tell me about some",
"heard of that movie.\", \"Wow that movie is new to me. I don't",
"I couldn't tell if you liked that \" \\ \"movie or not.\", \"Sorry",
"\"Wait.. did you like or dislike that movie?\", \"I think I need some",
"based on that one.\" ] return random.choice(responses) def utils_liked(): responses1 = [ \"Great,",
"understand, please put quotation marks around the \" \\ \"movie like this \\\"The",
"quotation marks are correct. \", \"It's hard for me to understand which movie",
"seen?\", \" Got any more opinions on movies you've seen?\", \" Any more",
"like {match}. Got it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay so {match}",
"hot takes?\", \" Any more movie opinions I should know?\", \" Anything else",
"] return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it! So you liked",
"So you liked {match}.\", f\"Okay so {match} was your type of movie.\", f\"Gotcha",
"didn't like that one as well.\", \"So you didn't like that one got",
"tell whether you \"\\ \"liked that movie or not.\", \"Hang on, I couldn't",
"random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_more_opinions():",
"I couldn't tell if you liked that movie or not.\" ] return random.choice(responses)",
"\"\\ \"in your response surrounding the movie title.\", \"I'm having trouble reading your",
"= [ \"Sorry, I couldn't tell if you liked that \" \\ \"movie",
"watched first.\", \"It's gonna be hard for me to give you some good",
"some more movies or say \"\\ \"'Recommendations please!' to hear my recommendations.\", \"",
"utils_liked(): responses1 = [ \"Great, glad you liked that one.\", \"Okay got it",
"Any other movies you've seen? \", \" Any more movie opinions I should",
"whether you \"\\ \"liked that movie or not.\", \"Hang on, I couldn't tell",
"anything about your tastes.\", \"I don't think I'm ready to give a recommendation",
"your movie huh.\", \"That movie wasn't for you then. I'll keep that in",
"responses = [ f\"Got it! So you liked {match}.\", f\"Okay so {match} was",
"response1 + response2 def utils_more_opinions(): responses = [ \" Now feel free to",
"\"on that one.\", \"That movie is actually unfamiliar to me.\", \"To be honest,",
"I haven't seen that movie before, so it'll \"\\ \"be hard to recommend",
"you liked {match}.\", f\"Sounds like {match} was right up your alley.\", f\"Okay so",
"know anything about your tastes.\", \"I don't think I'm ready to give a",
"didn't like.\", f\"{match} wasn't the movie for you then.\", f\"Got it you didn't",
"a good movie.\", \"Nice, sounds like that movie was right up your alley.\"",
"movie is new to me. I don't know much about it.\", \"I've actually",
"your quotation marks. \" \\ \"Try again.\", \"Uh oh, I don't think your",
"good movie.\", \"Nice, sounds like that movie was right up your alley.\" \"Wow",
"utils_disliked(): responses1 = [ \"Okay got it you didn't like that one.\", \"Gotcha",
"enjoyed that one.\", \"Good, glad you enjoyed it.\", \"Okay, got it, I think",
"did not like that one.\", ] responses2 = [ \" Now feel free",
"responses = [ \"Sorry, I couldn't tell if you liked that \" \\",
"didn't like that one.\", \"Gotcha so that wasn't the movie for you.\", \"Okay",
"feedback.\", \" What other movies have you seen?\", \" Any other movies you've",
"so {match} was your type of movie.\", f\"Gotcha so {match} was a good",
"random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad you liked that one.\", \"Okay",
"movie for you.\", \"Okay you didn't like that one.\", \"Yeah I've heard other",
"you.\", f\"Okay got it {match} wasn't your cup of tea.\", f\"So you did",
"your tastes.\", \"I don't think I'm ready to give a recommendation yet. \"\\",
"seen?\", \" Got any more hot takes?\", \" Any more movie opinions I",
"Can you please try again? \", ] return random.choice(responses) def utils_new_movie(): responses =",
"f\"Sounds like {match} was right up your alley.\", f\"Okay so your tastes align",
"like you enjoyed that one.\", \"Good, glad you enjoyed it.\", \"Okay, got it,",
"other people didn't like that one as well.\", \"So you didn't like that",
"my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it! So",
"\" Any more movies you've seen? \", \" You're giving me some great",
"that one.\", ] responses2 = [ \" Now feel free to tell me",
"hear my recommendations. \", \" Any more movies you've seen? \", \" You're",
"{match} was your type of movie.\", f\"Gotcha so {match} was a good fit",
"your tastes align with {match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses",
"about.\", \"To help me understand, please put quotation marks around the \" \\",
"utils_new_movie(): responses = [ \"Interesting, I haven't heard of that movie.\", \"Hmm I",
"\"Please tell me about some movies you watched first. \"\\ \"Then I'll be",
"honest, I haven't seen that movie before, so it'll \"\\ \"be hard to",
"I've heard other people didn't like that one as well.\", \"So you didn't",
"not like that one.\", ] responses2 = [ \" Now feel free to",
"I don't know much about it.\", \"I've actually never heard of that movie",
"means \\nI can't give you some good recommendations based \"\\ \"on that one.\",",
"free to tell me about some more movies or say \"\\ \"'Recommendations please!'",
"movies you've seen? \", \" Any more movie opinions I should know?\", \"",
"for you.\", \"Okay you didn't like that one.\", \"Yeah I've heard other people",
"this \\\"The Wizard of Oz\\\"\", \"It's hard for me to understand with your",
"\\ \"movie like this \\\"The Wizard of Oz\\\"\", \"It's hard for me to",
"aren't quite right.\", \"Please re-check your quotation marks. There should be two \"\\",
"\"Nice, sounds like that movie was right up your alley.\" \"Wow so you",
"based \"\\ \"on that one.\", \"That movie is actually unfamiliar to me.\", \"To",
"tell if you liked that \" \\ \"movie or not.\", \"Sorry I'm not",
"your quotation marks.\", \"Oops, seems like your quotation marks aren't quite right.\", \"Please",
"f\"{match} wasn't the movie for you then.\", f\"Got it you didn't like {match}.\"",
"\"\\ \"liked that movie or not.\", \"Hang on, I couldn't tell if you",
"like this \\\"The Wizard of Oz\\\"\", \"It's hard for me to understand with",
"1) < 0.3: response2 = random.choice(responses2) return response1 + response2 def utils_disliked(): responses1",
"\"'Recommendations please!' to hear my recommendations.\", \" Any more movies you've seen? \",",
"tea.\", f\"So you did not like {match}. Got it.\", f\"Gotcha so you didn't",
"movies. \"\\ \"I think you'll like my recommendations.\", \"Glad you liked the movie.\",",
"think I need some more information to tell whether you \"\\ \"liked that",
"\"It's hard for me to understand which movie you're talking about.\", \"To help",
"def utils_liked_match(match): responses = [ f\"Got it! So you liked {match}.\", f\"Okay so",
"actually unfamiliar to me.\", \"To be honest, I haven't seen that movie before,",
"f\"Okay so your tastes align with {match}, got it.\" ] return random.choice(responses) def",
"that movie?\", \"I think I need some more information to tell whether you",
"[ \"Sorry, I couldn't tell if you liked that \" \\ \"movie or",
"hard for me to give you some good \"\\ \"recommendations if I don't",
"glad you enjoyed it.\", \"Okay, got it, I think I have some other",
"think I'm ready to give a recommendation yet. \"\\ \"How about you tell",
"\" Got any more opinions on movies you've seen?\", \" Any more movie",
"= [ \" Now feel free to tell me about some more movies",
"that one as well.\", \"So you didn't like that one got it.\", \"That",
"be able to give you some great recommendations\" ] return random.choice(responses) def utils_quotations():",
"is actually unfamiliar to me.\", \"To be honest, I haven't seen that movie",
"seen?\", \" Any other movies you've seen?\", \" Got any more hot takes?\",",
"that movie or not.\", \"Wait.. did you like or dislike that movie?\", \"I",
"random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems like you messed up your",
"about some more movies or say \"\\ \"'Recommendations please!' to hear my recommendations.",
"enough information yet \"\\ \"to make a good recommendation.\", \"I can't give a",
"= [ \"Hmm seems like you messed up your quotation marks. \" \\",
"movies or say \"\\ \"'Recommendations please!' to hear my recommendations. \", \" Any",
"\" You're giving me some great feedback.\", \" What other movies have you",
"on that one.\" ] return random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad",
"opinion on a movie \"\\ \"before I can give you quality recommendations.\", \"Sorry,",
"so you like those kinds of movies. \"\\ \"I think you'll like my",
"some good \"\\ \"recommendations if I don't know anything about your tastes.\", \"I",
"] return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I haven't heard of",
"\"Interesting, I haven't heard of that movie.\", \"Hmm I haven't heard of that",
"what you think about that movie.\", \"I'm not quite sure if you liked",
"watched first. \"\\ \"Then I'll be able to give you some great recommendations\"",
"\"I can't quite tell what you think about that movie.\", \"I'm not quite",
"[ \" Now feel free to tell me about some more movies or",
"recommendations. \", \" Any more movies you've seen? \", \" You're giving me",
"random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses = [ \" Now feel",
"don't think I'm ready to give a recommendation yet. \"\\ \"How about you",
"random.choice(responses1) response2 = '' if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return",
"Now feel free to tell me about some more movies or say \"\\",
"recommendations.\", \" Any more movies you've seen? \", \" You're giving me some",
"cup of tea.\", f\"So you did not like {match}. Got it.\", f\"Gotcha so",
"for me to give you some good \"\\ \"recommendations if I don't know",
"didn't like {match}.\", f\"Okay so {match} was the movie you didn't like.\", f\"{match}",
"that movie.\", \"I'm not quite sure if you liked that movie or not.\",",
"the movie title.\", \"I'm having trouble reading your sentence because of the \"\\",
"give a good recommendation yet. Please \"\\ \"tell me about some movies you've",
"again? \", ] return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I haven't",
"movies you've watched?\", \"Please tell me about some movies you watched first. \"\\",
"\", ] return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I haven't heard",
"= [ \"Interesting, I haven't heard of that movie.\", \"Hmm I haven't heard",
"You're giving me some great feedback.\", \" What other movies have you seen?\",",
"\"I've actually never heard of that movie before! Unfortunately \"\\ \"that means \\nI",
"recommendation yet. Please \"\\ \"tell me about some movies you've watched first.\", \"It's",
"those kinds of movies. \"\\ \"I think you'll like my recommendations.\", \"Glad you",
"\\ \"movie or not.\", \"Sorry I'm not sure if you liked that one.\",",
"movie.\", f\"Gotcha so {match} was a good fit for you.\", f\"Okay got it",
"[ \"Great, glad you liked that one.\", \"Okay got it that was a",
"one got it.\", \"That really wasn't your movie huh.\", \"That movie wasn't for",
"\" What other movies have you seen? \", \" Any other movies you've",
"takes?\", \" Any more movie opinions I should know?\", \" Anything else you",
"\"I don't think I'm ready to give a recommendation yet. \"\\ \"How about",
"have you seen? \", \" Any other movies you've seen? \", \" Any",
"I have some other ones that you'll like as well.\", \"Awesome, glad you",
"good fit for you.\", f\"Okay got it you liked {match}.\", f\"Sounds like {match}",
"movie or not.\", \"Wait.. did you like or dislike that movie?\", \"I think",
"any more opinions on movies you've seen?\", \" Any more movie opinions I",
"\"It's hard for me to understand with your quotation marks.\", \"Oops, seems like",
"\"Gotcha so that wasn't the movie for you.\", \"Okay you didn't like that",
"like your quotation marks aren't quite right.\", \"Please re-check your quotation marks. There",
"it you liked {match}.\", f\"Sounds like {match} was right up your alley.\", f\"Okay",
"{match}.\" ] return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I couldn't tell",
"movie \"\\ \"before I can give you quality recommendations.\", \"Sorry, I don't have",
"tell me about some more movies or say \"\\ \"'Recommendations please!' to hear",
"first. \"\\ \"Then I'll be able to give you some great recommendations\" ]",
"before! Unfortunately \"\\ \"that means \\nI can't give you some good recommendations based",
"me to give you some good \"\\ \"recommendations if I don't know anything",
"one.\" ] return random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad you liked",
"about that movie.\", \"I'm not quite sure if you liked that movie or",
"\"To be honest, I haven't seen that movie before, so it'll \"\\ \"be",
"was right up your alley.\" \"Wow so you like those kinds of movies.",
"[ \"Sorry, I need your opinion on a movie \"\\ \"before I can",
"heard of that movie.\", \"Hmm I haven't heard of that movie.\", \"Wow that",
"that one.\" ] return random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad you",
"I'm ready to give a recommendation yet. \"\\ \"How about you tell me",
"surrounding the movie title.\", \"I'm having trouble reading your sentence because of the",
"wasn't the movie for you then.\", f\"Got it you didn't like {match}.\" ]",
"[ \"Interesting, I haven't heard of that movie.\", \"Hmm I haven't heard of",
"was a good fit for you.\", f\"Okay got it you liked {match}.\", f\"Sounds",
"you want to tell me before I give my recommendations?\" ] return random.choice(responses)",
"think about that movie.\", \"I'm not quite sure if you liked that movie",
"one.\", \"I can't quite tell what you think about that movie.\", \"I'm not",
"other ones that you'll like as well.\", \"Awesome, glad you liked it.\" ]",
"like as well.\", \"Awesome, glad you liked it.\" ] responses2 = [ \"",
"of that movie.\", \"Wow that movie is new to me. I don't know",
"great recommendations\" ] return random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems like",
"please!' to hear my recommendations.\", \" Any more movies you've seen? \", \"",
"in mind.\", \"Okay so you did not like that one.\", ] responses2 =",
"that movie was right up your alley.\" \"Wow so you like those kinds",
"you didn't like that one.\", \"Gotcha so that wasn't the movie for you.\",",
"you some good \"\\ \"recommendations if I don't know anything about your tastes.\",",
"was your type of movie.\", f\"Gotcha so {match} was a good fit for",
"\"That movie wasn't for you then. I'll keep that in mind.\", \"Okay so",
"0.3: response2 = random.choice(responses2) return response1 + response2 def utils_disliked(): responses1 = [",
"have you seen?\", \" Any other movies you've seen?\", \" Got any more",
"= [ \"Okay got it you didn't like that one.\", \"Gotcha so that",
"to understand with your quotation marks.\", \"Oops, seems like your quotation marks aren't",
"got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds like",
"\"That movie is actually unfamiliar to me.\", \"To be honest, I haven't seen",
"\"How about you tell me about some movies you've watched?\", \"Please tell me",
"as well.\", \"So you didn't like that one got it.\", \"That really wasn't",
"opinions on movies you've seen?\", \" Any more movie opinions I should know?\",",
"seen?\", \" Any more movie opinions I should know?\", \" Anything else you",
"like my recommendations.\", \"Glad you liked the movie.\", \"Sounds like you enjoyed that",
"random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I haven't heard of that movie.\",",
"f\"So you did not like {match}. Got it.\", f\"Gotcha so you didn't like",
"that one.\", \"Gotcha so that wasn't the movie for you.\", \"Okay you didn't",
"0.3: response2 = random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses = [",
"utils_quotations(): responses = [ \"Hmm seems like you messed up your quotation marks.",
"movie you're talking about.\", \"To help me understand, please put quotation marks around",
"responses1 = [ \"Great, glad you liked that one.\", \"Okay got it that",
"ones that you'll like as well.\", \"Awesome, glad you liked it.\" ] responses2",
"response2 = '' if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1",
"can give you quality recommendations.\", \"Sorry, I don't have enough information yet \"\\",
"need your opinion on a movie \"\\ \"before I can give you quality",
"feedback.\", \" What other movies have you seen? \", \" Any other movies",
"utils_more_opinions(): responses = [ \" Now feel free to tell me about some",
"\"\\ \"'Recommendations please!' to hear my recommendations. \", \" Any more movies you've",
"my recommendations.\", \" Any more movies you've seen? \", \" You're giving me",
"movie for you then.\", f\"Got it you didn't like {match}.\" ] return random.choice(responses)",
"can't give a good recommendation yet. Please \"\\ \"tell me about some movies",
"that movie.\", \"Wow that movie is new to me. I don't know much",
"me. I don't know much about it.\", \"I've actually never heard of that",
"responses1 = [ \"Okay got it you didn't like that one.\", \"Gotcha so",
"that you'll like as well.\", \"Awesome, glad you liked it.\" ] responses2 =",
"able to give you some great recommendations\" ] return random.choice(responses) def utils_quotations(): responses",
"\"Sorry, I couldn't tell if you liked that \" \\ \"movie or not.\",",
"return response1 + response2 def utils_disliked(): responses1 = [ \"Okay got it you",
"\"\\ \"tell me about some movies you've watched first.\", \"It's gonna be hard",
"oh, I don't think your quotation marks are correct. \", \"It's hard for",
"say \"\\ \"'Recommendations please!' to hear my recommendations. \", \" Any more movies",
"\"It's gonna be hard for me to give you some good \"\\ \"recommendations",
"liked that movie or not.\", \"Wait.. did you like or dislike that movie?\",",
"that one.\", \"That movie is actually unfamiliar to me.\", \"To be honest, I",
"recommendations.\", \"Glad you liked the movie.\", \"Sounds like you enjoyed that one.\", \"Good,",
"Got any more opinions on movies you've seen?\", \" Any more movie opinions",
"] response1 = random.choice(responses1) response2 = '' if random.uniform(0, 1) < 0.3: response2",
"don't know much about it.\", \"I've actually never heard of that movie before!",
"def utils_disliked(): responses1 = [ \"Okay got it you didn't like that one.\",",
"return response1 + response2 def utils_more_opinions(): responses = [ \" Now feel free",
"tell me about some movies you watched first. \"\\ \"Then I'll be able",
"There should be two \"\\ \"in your response surrounding the movie title.\", \"I'm",
"I think I have some other ones that you'll like as well.\", \"Awesome,",
"I should know?\", \" Anything else you want to tell me before I",
"return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I couldn't tell if you",
"def utils_disliked_match(match): responses = [ f\"Okay sounds like {match} wasn't the \" \\",
"to give you some great recommendations\" ] return random.choice(responses) def utils_quotations(): responses =",
"of Oz\\\"\", \"It's hard for me to understand with your quotation marks.\", \"Oops,",
"seen? \", \" You're giving me some great feedback.\", \" What other movies",
"to give you some good \"\\ \"recommendations if I don't know anything about",
"you've seen? \", \" You're giving me some great feedback.\", \" What other",
"\" \\ \"movie for you.\", f\"Okay got it {match} wasn't your cup of",
"\"quotation marks. Can you please try again? \", ] return random.choice(responses) def utils_new_movie():",
"got it you didn't like that one.\", \"Gotcha so that wasn't the movie",
"re-check your quotation marks. There should be two \"\\ \"in your response surrounding",
"Any more movie opinions I should know?\", \" Anything else you want to",
"your quotation marks. There should be two \"\\ \"in your response surrounding the",
"of the \"\\ \"quotation marks. Can you please try again? \", ] return",
"\" Any other movies you've seen? \", \" Any more movie opinions I",
"\"\\ \"'Recommendations please!' to hear my recommendations.\", \" Any more movies you've seen?",
"my recommendations. \", \" Any more movies you've seen? \", \" You're giving",
"it'll \"\\ \"be hard to recommend you a movie based on that one.\"",
"more movie opinions I should know?\", \" Anything else you want to tell",
"for you.\", f\"Okay got it you liked {match}.\", f\"Sounds like {match} was right",
"response2 def utils_disliked(): responses1 = [ \"Okay got it you didn't like that",
"people didn't like that one as well.\", \"So you didn't like that one",
"like that one.\", \"Gotcha so that wasn't the movie for you.\", \"Okay you",
"like {match} wasn't the \" \\ \"movie for you.\", f\"Okay got it {match}",
"messed up your quotation marks. \" \\ \"Try again.\", \"Uh oh, I don't",
"sounds like {match} wasn't the \" \\ \"movie for you.\", f\"Okay got it",
"some more information to tell whether you \"\\ \"liked that movie or not.\",",
"want to tell me before I give my recommendations?\" ] return random.choice(responses) def",
"I haven't heard of that movie.\", \"Wow that movie is new to me.",
"of that movie.\", \"Hmm I haven't heard of that movie.\", \"Wow that movie",
"one as well.\", \"So you didn't like that one got it.\", \"That really",
"movie or not.\", \"Hang on, I couldn't tell if you liked that movie",
"right up your alley.\" \"Wow so you like those kinds of movies. \"\\",
"sounds like that movie was right up your alley.\" \"Wow so you like",
"gonna be hard for me to give you some good \"\\ \"recommendations if",
"utils_min_required(): responses = [ \"Sorry, I need your opinion on a movie \"\\",
"\"Good, glad you enjoyed it.\", \"Okay, got it, I think I have some",
"not.\", \"Hang on, I couldn't tell if you liked that movie or not.\"",
"f\"Got it you didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses =",
"like that one as well.\", \"So you didn't like that one got it.\",",
"actually never heard of that movie before! Unfortunately \"\\ \"that means \\nI can't",
"def utils_more_opinions(): responses = [ \" Now feel free to tell me about",
"\"I'm having trouble reading your sentence because of the \"\\ \"quotation marks. Can",
"wasn't your movie huh.\", \"That movie wasn't for you then. I'll keep that",
"marks. There should be two \"\\ \"in your response surrounding the movie title.\",",
"that one.\", \"I can't quite tell what you think about that movie.\", \"I'm",
"\" \\ \"movie or not.\", \"Sorry I'm not sure if you liked that",
"think you'll like my recommendations.\", \"Glad you liked the movie.\", \"Sounds like you",
"me understand, please put quotation marks around the \" \\ \"movie like this",
"other movies you've seen? \", \" Any more movie opinions I should know?\",",
"you've seen?\", \" Got any more opinions on movies you've seen?\", \" Any",
"] return random.choice(responses) def utils_low_confidence(): responses = [ \"Sorry, I couldn't tell if",
"if you liked that one.\", \"I can't quite tell what you think about",
"\", \" Any other movies you've seen? \", \" Any more movie opinions",
"{match} wasn't your cup of tea.\", f\"So you did not like {match}. Got",
"that one got it.\", \"That really wasn't your movie huh.\", \"That movie wasn't",
"right.\", \"Please re-check your quotation marks. There should be two \"\\ \"in your",
"f\"Okay got it you liked {match}.\", f\"Sounds like {match} was right up your",
"I'm not sure if you liked that one.\", \"I can't quite tell what",
"\"that means \\nI can't give you some good recommendations based \"\\ \"on that",
"or say \"\\ \"'Recommendations please!' to hear my recommendations. \", \" Any more",
"give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it!",
"responses = [ \"Sorry, I need your opinion on a movie \"\\ \"before",
"for me to understand with your quotation marks.\", \"Oops, seems like your quotation",
"recommendation.\", \"I can't give a good recommendation yet. Please \"\\ \"tell me about",
"recommendations?\" ] response1 = random.choice(responses1) response2 = '' if random.uniform(0, 1) < 0.3:",
"again.\", \"Uh oh, I don't think your quotation marks are correct. \", \"It's",
"liked {match}.\", f\"Okay so {match} was your type of movie.\", f\"Gotcha so {match}",
"f\"Okay so {match} was your type of movie.\", f\"Gotcha so {match} was a",
"your alley.\", f\"Okay so your tastes align with {match}, got it.\" ] return",
"quotation marks around the \" \\ \"movie like this \\\"The Wizard of Oz\\\"\",",
"are correct. \", \"It's hard for me to understand which movie you're talking",
"I can give you quality recommendations.\", \"Sorry, I don't have enough information yet",
"movie.\", \"Nice, sounds like that movie was right up your alley.\" \"Wow so",
"should know?\", \" Anything else you want to tell me before I give",
"seems like you messed up your quotation marks. \" \\ \"Try again.\", \"Uh",
"marks are correct. \", \"It's hard for me to understand which movie you're",
"= [ f\"Okay sounds like {match} wasn't the \" \\ \"movie for you.\",",
"or not.\", \"Hang on, I couldn't tell if you liked that movie or",
"giving me some great feedback.\", \" What other movies have you seen? \",",
"great feedback.\", \" What other movies have you seen?\", \" Any other movies",
"more hot takes?\", \" Any more movie opinions I should know?\", \" Anything",
"giving me some great feedback.\", \" What other movies have you seen?\", \"",
"[ f\"Okay sounds like {match} wasn't the \" \\ \"movie for you.\", f\"Okay",
"or not.\", \"Wait.. did you like or dislike that movie?\", \"I think I",
"\" Anything else you want to tell me before I give my recommendations?\"",
"about you tell me about some movies you've watched?\", \"Please tell me about",
"\" Any other movies you've seen?\", \" Got any more opinions on movies",
"before I give my recommendations?\" ] response1 = random.choice(responses1) response2 = '' if",
"= random.choice(responses2) return response1 + response2 def utils_disliked(): responses1 = [ \"Okay got",
"\"movie like this \\\"The Wizard of Oz\\\"\", \"It's hard for me to understand",
"you quality recommendations.\", \"Sorry, I don't have enough information yet \"\\ \"to make",
"recommendations\" ] return random.choice(responses) def utils_quotations(): responses = [ \"Hmm seems like you",
"\"Awesome, glad you liked it.\" ] responses2 = [ \" Now feel free",
"\"Wow that movie is new to me. I don't know much about it.\",",
"be honest, I haven't seen that movie before, so it'll \"\\ \"be hard",
"make a good recommendation.\", \"I can't give a good recommendation yet. Please \"\\",
"you'll like as well.\", \"Awesome, glad you liked it.\" ] responses2 = [",
"was a good movie.\", \"Nice, sounds like that movie was right up your",
"quite tell what you think about that movie.\", \"I'm not quite sure if",
"you like those kinds of movies. \"\\ \"I think you'll like my recommendations.\",",
"movie wasn't for you then. I'll keep that in mind.\", \"Okay so you",
"you some good recommendations based \"\\ \"on that one.\", \"That movie is actually",
"\"Okay so you did not like that one.\", ] responses2 = [ \"",
"{match} was the movie you didn't like.\", f\"{match} wasn't the movie for you",
"movies you've seen?\", \" Got any more hot takes?\", \" Any more movie",
"not quite sure if you liked that movie or not.\", \"Wait.. did you",
"= random.choice(responses2) return response1 + response2 def utils_more_opinions(): responses = [ \" Now",
"that movie before, so it'll \"\\ \"be hard to recommend you a movie",
"help me understand, please put quotation marks around the \" \\ \"movie like",
"to hear my recommendations.\", \" Any more movies you've seen? \", \" You're",
"your sentence because of the \"\\ \"quotation marks. Can you please try again?",
"that was a good movie.\", \"Nice, sounds like that movie was right up",
"like that one got it.\", \"That really wasn't your movie huh.\", \"That movie",
"f\"Got it! So you liked {match}.\", f\"Okay so {match} was your type of",
"{match}. Got it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay so {match} was",
"didn't like that one.\", \"Yeah I've heard other people didn't like that one",
"\"Yeah I've heard other people didn't like that one as well.\", \"So you",
"= '' if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1 +",
"\\ \"Try again.\", \"Uh oh, I don't think your quotation marks are correct.",
"marks around the \" \\ \"movie like this \\\"The Wizard of Oz\\\"\", \"It's",
"\"I can't give a good recommendation yet. Please \"\\ \"tell me about some",
"is new to me. I don't know much about it.\", \"I've actually never",
"one.\", \"Okay got it that was a good movie.\", \"Nice, sounds like that",
"{match} wasn't the \" \\ \"movie for you.\", f\"Okay got it {match} wasn't",
"\"Please re-check your quotation marks. There should be two \"\\ \"in your response",
"\"\\ \"that means \\nI can't give you some good recommendations based \"\\ \"on",
"\"Hmm I haven't heard of that movie.\", \"Wow that movie is new to",
"did not like {match}. Got it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay",
"\"movie or not.\", \"Sorry I'm not sure if you liked that one.\", \"I",
"think your quotation marks are correct. \", \"It's hard for me to understand",
"\"Hmm seems like you messed up your quotation marks. \" \\ \"Try again.\",",
"quotation marks aren't quite right.\", \"Please re-check your quotation marks. There should be",
"+ response2 def utils_more_opinions(): responses = [ \" Now feel free to tell",
"it! So you liked {match}.\", f\"Okay so {match} was your type of movie.\",",
"sure if you liked that one.\", \"I can't quite tell what you think",
"movie.\", \"I'm not quite sure if you liked that movie or not.\", \"Wait..",
"don't have enough information yet \"\\ \"to make a good recommendation.\", \"I can't",
"so your tastes align with {match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match):",
"so that wasn't the movie for you.\", \"Okay you didn't like that one.\",",
"quite right.\", \"Please re-check your quotation marks. There should be two \"\\ \"in",
"] return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds like {match} wasn't",
"my recommendations?\" ] response1 = random.choice(responses1) response2 = '' if random.uniform(0, 1) <",
"\"before I can give you quality recommendations.\", \"Sorry, I don't have enough information",
"that movie before! Unfortunately \"\\ \"that means \\nI can't give you some good",
"give you quality recommendations.\", \"Sorry, I don't have enough information yet \"\\ \"to",
"tell what you think about that movie.\", \"I'm not quite sure if you",
"other movies have you seen? \", \" Any other movies you've seen? \",",
"my recommendations.\", \"Glad you liked the movie.\", \"Sounds like you enjoyed that one.\",",
"you did not like {match}. Got it.\", f\"Gotcha so you didn't like {match}.\",",
"try again? \", ] return random.choice(responses) def utils_new_movie(): responses = [ \"Interesting, I",
"{match}.\", f\"Okay so {match} was the movie you didn't like.\", f\"{match} wasn't the",
"so {match} was the movie you didn't like.\", f\"{match} wasn't the movie for",
"movie you didn't like.\", f\"{match} wasn't the movie for you then.\", f\"Got it",
"\"Wow so you like those kinds of movies. \"\\ \"I think you'll like",
"more movies you've seen? \", \" You're giving me some great feedback.\", \"",
"\"Okay, got it, I think I have some other ones that you'll like",
"return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it! So you liked {match}.\",",
"Anything else you want to tell me before I give my recommendations?\" ]",
"about your tastes.\", \"I don't think I'm ready to give a recommendation yet.",
"your type of movie.\", f\"Gotcha so {match} was a good fit for you.\",",
"some other ones that you'll like as well.\", \"Awesome, glad you liked it.\"",
"was the movie you didn't like.\", f\"{match} wasn't the movie for you then.\",",
"I don't think your quotation marks are correct. \", \"It's hard for me",
"tell me about some movies you've watched?\", \"Please tell me about some movies",
"quite sure if you liked that movie or not.\", \"Wait.. did you like",
"couldn't tell if you liked that \" \\ \"movie or not.\", \"Sorry I'm",
"that \" \\ \"movie or not.\", \"Sorry I'm not sure if you liked",
"alley.\" \"Wow so you like those kinds of movies. \"\\ \"I think you'll",
"\"\\ \"How about you tell me about some movies you've watched?\", \"Please tell",
"that movie is new to me. I don't know much about it.\", \"I've",
"it you didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses = [",
"so you did not like that one.\", ] responses2 = [ \" Now",
"yet \"\\ \"to make a good recommendation.\", \"I can't give a good recommendation",
"with {match}, got it.\" ] return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay",
"utils_low_confidence(): responses = [ \"Sorry, I couldn't tell if you liked that \"",
"a movie based on that one.\" ] return random.choice(responses) def utils_liked(): responses1 =",
"Got it.\", f\"Gotcha so you didn't like {match}.\", f\"Okay so {match} was the",
"with your quotation marks.\", \"Oops, seems like your quotation marks aren't quite right.\",",
"\"\\ \"Then I'll be able to give you some great recommendations\" ] return",
"\"\\ \"on that one.\", \"That movie is actually unfamiliar to me.\", \"To be",
"\"To help me understand, please put quotation marks around the \" \\ \"movie",
"response2 def utils_more_opinions(): responses = [ \" Now feel free to tell me",
"to tell me about some more movies or say \"\\ \"'Recommendations please!' to",
"utils_liked_match(match): responses = [ f\"Got it! So you liked {match}.\", f\"Okay so {match}",
"return random.choice(responses) def utils_liked(): responses1 = [ \"Great, glad you liked that one.\",",
"marks. Can you please try again? \", ] return random.choice(responses) def utils_new_movie(): responses",
"{match}.\", f\"Okay so {match} was your type of movie.\", f\"Gotcha so {match} was",
"What other movies have you seen? \", \" Any other movies you've seen?",
"your opinion on a movie \"\\ \"before I can give you quality recommendations.\",",
"response1 + response2 def utils_disliked(): responses1 = [ \"Okay got it you didn't",
"of that movie before! Unfortunately \"\\ \"that means \\nI can't give you some",
"like that movie was right up your alley.\" \"Wow so you like those",
"\"I think I need some more information to tell whether you \"\\ \"liked",
"you seen?\", \" Any other movies you've seen?\", \" Got any more opinions",
"information to tell whether you \"\\ \"liked that movie or not.\", \"Hang on,",
"some movies you watched first. \"\\ \"Then I'll be able to give you",
"else you want to tell me before I give my recommendations?\" ] response1",
"\"Okay got it you didn't like that one.\", \"Gotcha so that wasn't the",
"sentence because of the \"\\ \"quotation marks. Can you please try again? \",",
"movies you've seen? \", \" You're giving me some great feedback.\", \" What",
"import random def utils_min_required(): responses = [ \"Sorry, I need your opinion on",
"you liked that one.\", \"Okay got it that was a good movie.\", \"Nice,",
"\"I think you'll like my recommendations.\", \"Glad you liked the movie.\", \"Sounds like",
"enjoyed it.\", \"Okay, got it, I think I have some other ones that",
"it.\" ] return random.choice(responses) def utils_disliked_match(match): responses = [ f\"Okay sounds like {match}",
"movie before, so it'll \"\\ \"be hard to recommend you a movie based",
"great feedback.\", \" What other movies have you seen? \", \" Any other",
"mind.\", \"Okay so you did not like that one.\", ] responses2 = [",
"it {match} wasn't your cup of tea.\", f\"So you did not like {match}.",
"liked that \" \\ \"movie or not.\", \"Sorry I'm not sure if you",
"def utils_new_movie(): responses = [ \"Interesting, I haven't heard of that movie.\", \"Hmm",
"you.\", f\"Okay got it you liked {match}.\", f\"Sounds like {match} was right up",
"should be two \"\\ \"in your response surrounding the movie title.\", \"I'm having",
"about it.\", \"I've actually never heard of that movie before! Unfortunately \"\\ \"that",
"if random.uniform(0, 1) < 0.3: response2 = random.choice(responses2) return response1 + response2 def",
"\"So you didn't like that one got it.\", \"That really wasn't your movie",
"\"I'm not quite sure if you liked that movie or not.\", \"Wait.. did",
"\"Okay got it that was a good movie.\", \"Nice, sounds like that movie",
"it you didn't like that one.\", \"Gotcha so that wasn't the movie for",
"to tell me before I give my recommendations?\" ] response1 = random.choice(responses1) response2",
"responses = [ \" Now feel free to tell me about some more",
"quality recommendations.\", \"Sorry, I don't have enough information yet \"\\ \"to make a",
"What other movies have you seen?\", \" Any other movies you've seen?\", \"",
"got it you liked {match}.\", f\"Sounds like {match} was right up your alley.\",",
"be hard for me to give you some good \"\\ \"recommendations if I",
"really wasn't your movie huh.\", \"That movie wasn't for you then. I'll keep",
"to understand which movie you're talking about.\", \"To help me understand, please put",
"you tell me about some movies you've watched?\", \"Please tell me about some",
"up your quotation marks. \" \\ \"Try again.\", \"Uh oh, I don't think",
"a movie \"\\ \"before I can give you quality recommendations.\", \"Sorry, I don't",
"yet. \"\\ \"How about you tell me about some movies you've watched?\", \"Please",
"give my recommendations?\" ] response1 = random.choice(responses1) response2 = '' if random.uniform(0, 1)",
"as well.\", \"Awesome, glad you liked it.\" ] responses2 = [ \" Now",
"\"'Recommendations please!' to hear my recommendations. \", \" Any more movies you've seen?",
"me some great feedback.\", \" What other movies have you seen? \", \"",
"the movie you didn't like.\", f\"{match} wasn't the movie for you then.\", f\"Got",
"have enough information yet \"\\ \"to make a good recommendation.\", \"I can't give",
"glad you liked that one.\", \"Okay got it that was a good movie.\",",
"seems like your quotation marks aren't quite right.\", \"Please re-check your quotation marks.",
"responses = [ \"Hmm seems like you messed up your quotation marks. \"",
"movie is actually unfamiliar to me.\", \"To be honest, I haven't seen that",
"be two \"\\ \"in your response surrounding the movie title.\", \"I'm having trouble",
"have some other ones that you'll like as well.\", \"Awesome, glad you liked",
"before I give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses = [",
"= [ f\"Got it! So you liked {match}.\", f\"Okay so {match} was your",
"\"Glad you liked the movie.\", \"Sounds like you enjoyed that one.\", \"Good, glad",
"I need your opinion on a movie \"\\ \"before I can give you",
"your quotation marks aren't quite right.\", \"Please re-check your quotation marks. There should",
"\"be hard to recommend you a movie based on that one.\" ] return",
"you liked {match}.\", f\"Okay so {match} was your type of movie.\", f\"Gotcha so",
"movie.\", \"Sounds like you enjoyed that one.\", \"Good, glad you enjoyed it.\", \"Okay,",
"response surrounding the movie title.\", \"I'm having trouble reading your sentence because of",
"your response surrounding the movie title.\", \"I'm having trouble reading your sentence because",
"movies you've seen?\", \" Got any more opinions on movies you've seen?\", \"",
"random.choice(responses2) return response1 + response2 def utils_disliked(): responses1 = [ \"Okay got it",
"give a recommendation yet. \"\\ \"How about you tell me about some movies",
"seen? \", \" Any other movies you've seen? \", \" Any more movie",
"keep that in mind.\", \"Okay so you did not like that one.\", ]",
"movies you've seen?\", \" Any more movie opinions I should know?\", \" Anything",
"or not.\", \"Sorry I'm not sure if you liked that one.\", \"I can't",
"recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got it! So you",
"like {match} was right up your alley.\", f\"Okay so your tastes align with",
"good \"\\ \"recommendations if I don't know anything about your tastes.\", \"I don't",
"much about it.\", \"I've actually never heard of that movie before! Unfortunately \"\\",
"of tea.\", f\"So you did not like {match}. Got it.\", f\"Gotcha so you",
"well.\", \"So you didn't like that one got it.\", \"That really wasn't your",
"unfamiliar to me.\", \"To be honest, I haven't seen that movie before, so",
"movies you watched first. \"\\ \"Then I'll be able to give you some",
"def utils_min_required(): responses = [ \"Sorry, I need your opinion on a movie",
"you enjoyed it.\", \"Okay, got it, I think I have some other ones",
"movie opinions I should know?\", \" Anything else you want to tell me",
"{match} was right up your alley.\", f\"Okay so your tastes align with {match},",
"your alley.\" \"Wow so you like those kinds of movies. \"\\ \"I think",
"good recommendations based \"\\ \"on that one.\", \"That movie is actually unfamiliar to",
"other movies have you seen?\", \" Any other movies you've seen?\", \" Got",
"utils_disliked_match(match): responses = [ f\"Okay sounds like {match} wasn't the \" \\ \"movie",
"then.\", f\"Got it you didn't like {match}.\" ] return random.choice(responses) def utils_low_confidence(): responses",
"on a movie \"\\ \"before I can give you quality recommendations.\", \"Sorry, I",
"got it.\", \"That really wasn't your movie huh.\", \"That movie wasn't for you",
"response2 = random.choice(responses2) return response1 + response2 def utils_disliked(): responses1 = [ \"Okay",
"I give my recommendations?\" ] return random.choice(responses) def utils_liked_match(match): responses = [ f\"Got",
"responses2 = [ \" Now feel free to tell me about some more",
"\"\\ \"quotation marks. Can you please try again? \", ] return random.choice(responses) def",
"\"Uh oh, I don't think your quotation marks are correct. \", \"It's hard",
"tastes.\", \"I don't think I'm ready to give a recommendation yet. \"\\ \"How",
"hard for me to understand which movie you're talking about.\", \"To help me",
"quotation marks. There should be two \"\\ \"in your response surrounding the movie",
"you a movie based on that one.\" ] return random.choice(responses) def utils_liked(): responses1",
"so you didn't like {match}.\", f\"Okay so {match} was the movie you didn't",
"can't give you some good recommendations based \"\\ \"on that one.\", \"That movie",
"one.\", \"Yeah I've heard other people didn't like that one as well.\", \"So"
] |
[
"'%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common setting relative_height",
"Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40, devT = development_parameters, leaves =",
"0, output_directory = Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df",
"= float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. /",
"Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file =",
"povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file =",
"locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and",
"TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind",
"= Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene",
"result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output,",
"povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind",
"parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential",
"RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R,",
"sim_width, length = dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area =",
"del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area,",
"= float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) # m,",
"else: result_df = new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0]",
"domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light,",
"cm = Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0] T = RT[:,1]",
"Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm'])",
"1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True}",
"TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind",
"Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output)",
"[120] dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene,",
"Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh,",
"if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in",
"'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} #",
"FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width = 12.0",
"[0] Zenith_fisheye = [0] sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants, New_domain,",
"Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary",
"# Common setting relative_height = 200 # camera above the canopy # Green",
"duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene",
"= pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel # Save geometry file name_canopy",
"Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil,",
"= float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 =",
"interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40, devT =",
"import os from adel import AdelR from adel.geometric_elements import Leaves from adel.AdelR import",
"= path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and move forward!!!***'",
"'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the",
"import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract,",
"= Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0]",
"Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) #",
"canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain",
"Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical,",
"= float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2,",
"(need large scene) if Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n =",
"if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green fraction if GF:",
"= relative_height, z_top = z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path,",
"= float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']),",
"incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves",
"= TT, Ind = Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width =",
"Adel_output) if TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh =",
"import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs",
"float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration':",
"image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) #",
"z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT, Ind = Ind)",
"# m, generate three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars =",
"import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import",
"= Adel_output, thermal = TT, Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh",
"= povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df'",
"Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if",
"phenotyping experiments 11/09/2017 <NAME> ''' import os from adel import AdelR from adel.geometric_elements",
"2000, relative_height = relative_height, output_directory = Adel_output) if TT in Sunlit_TT: for A_sun",
"Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR",
"= Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501) R",
"povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not",
"Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save",
"= 40, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT",
"Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df =",
"z_top = 0, output_directory = Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df])",
"T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene,",
"adel.povray.povray_ind import povray_Green from pyDOE import * from scipy.stats import uniform from openalea.core.path",
"except TypeError: print 'Pass it and move forward!!!***' result_df_path = [] pass return",
"= path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry file name_canopy",
"/ 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty':",
"sampling_times = 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width,",
"= GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory =",
"povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height = 2000,",
"range(400, 2501) R = RT[:,0] T = RT[:,1] for wave in Waves_camera: Plant_optical",
"GF_camera = [], FAPAR = False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral",
"plot_df = new_plot_df del Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if",
"= False): try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length",
"Adel_output, thermal = TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal",
"= [], Zenith_GF = [], FAPAR = True, GF = True, Multi_spectral =",
"os from adel import AdelR from adel.geometric_elements import Leaves from adel.AdelR import R_xydb,",
"povfile_box, thermal = TT, Ind = Ind, cameras = cameras, image_height = GF_camera['image_height'],",
"if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common setting relative_height =",
"= False, Ray_camera = [], Ray_light = []): try: # Adel parameters development_parameters",
"z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width = 2000,",
"Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file",
"Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel",
"nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel #",
"povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras =",
"from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors",
"Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave = range(400,",
"float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) # m, generate three rows dup_length",
"Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20, devT = development_parameters, leaves =",
"fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'],",
"= RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref",
"move forward!!!***' result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output,",
"False): try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length =",
"= Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0] T = RT[:,1] for",
"from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as pd from adel.plantgen import",
"[], Sunlit_Ang = [], Multi_spectral = False, Ray_camera = [], Ray_light = []):",
"plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del",
"path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0]",
"Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing,",
"plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path,",
"= {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2,",
"'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern table to",
"= float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink':",
"= Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm =",
"import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail",
"adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF,",
"# Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth",
"= float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 =",
"= Adel_output, thermal = TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box,",
"z_top = z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width",
"GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory = Adel_output) if 'result_df' in",
"= Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun = A_sun,",
"Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] #",
"TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else:",
"= Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind,",
"Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it and move",
"Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral = False, Ray_camera = [], Ray_light",
"result_df = new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye",
"= 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']),",
"= float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density =",
"Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del",
"output_directory = Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df =",
"import * from scipy.stats import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import",
"= Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye,",
"relative_height = relative_height, output_directory = Adel_output) if TT in Sunlit_TT: for A_sun in",
"2501) R = RT[:,0] T = RT[:,1] for wave in Waves_camera: Plant_optical =",
"[]): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']),",
"povray_Green from pyDOE import * from scipy.stats import uniform from openalea.core.path import path",
"del Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output +",
"thermal = TT, Ind = Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width",
"= Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain,",
"{'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en':",
"soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical,",
"2501) R = RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical =",
"= GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box,",
"float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']),",
"if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width =",
"soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref,",
"T = RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T)",
"adel.plantgen import plantgen_interface import numpy as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy",
"import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter",
"Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as pd from adel.plantgen",
"dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain = New_domain",
"Full_wave = range(400, 2501) R = RT[:,0] T = RT[:,1] for wave in",
"= path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv')))",
"= Ind, cameras = cameras, image_height = 1000, image_width = 1000, relative_height =",
"Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from",
"povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene = False, GF",
"del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for",
"new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras = cameras,",
"plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import * from scipy.stats",
"locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for FAPAR if",
"cw = Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0]",
"= Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0] T",
"import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind,",
"povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun =",
"= Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras = cameras, image_height",
"for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave,",
"= [10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0]",
"distribution pattern table to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate",
"def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene = False, GF =",
"povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it and move forward!!!***' result_df_path =",
"= Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type",
"= Adel_output) # Simulate BRDF (need large scene) if Multi_spectral: # Setting of",
"Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf':",
"get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from",
"= [0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width = 12.0 sampling_times =",
"Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new,",
"soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it and move forward!!!***'",
"Adel_output) # Simulate BRDF (need large scene) if Multi_spectral: # Setting of prosail",
"adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as pd from adel.plantgen import plantgen_interface",
"nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary",
"= GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing",
"function to conduct phenotyping experiments 11/09/2017 <NAME> ''' import os from adel import",
"incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline =",
"pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']),",
"+ name_canopy, 'BGEOM') # Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras =",
"float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration':",
"= float(Param['Density']), duplicate = 20, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars",
"sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory =",
"Green fraction if GF: Azimuth = [0] fov = [10] sampling_times = 4",
"# Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 =",
"'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals():",
"Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0] T = RT[:,1] for wave",
"import numpy as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from",
"N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf =",
"Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df",
"= False,save_scene = False, GF = False, GF_camera = [], FAPAR = False,",
"plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel # Save geometry file",
"domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output,",
"index=False) except TypeError: print 'Pass it and move forward!!!***' result_df_path = [] pass",
"canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del",
"povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it",
"dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) # m, generate three",
"wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin =",
"cameras = cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width = 2000, relative_height",
"image_width = 2000, relative_height = relative_height, output_directory = Adel_output) if TT in Sunlit_TT:",
"= Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new,",
"FAPAR = True, GF = True, Multi_spectral = False, save_scene = False): try:",
"Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov =",
"1000, relative_height = relative_height, z_top = z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output,",
"'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel #",
"Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun",
"index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError:",
"= float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width =",
"if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print",
"= GF_camera['distance'], z_top = 0, output_directory = Adel_output) if 'result_df' in locals(): result_df",
"= dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain,",
"new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df",
"AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from",
"= Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel",
"FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times = 7 dup_width = 8.0",
"= Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera,",
"povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera,",
"table to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40,",
"Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene =",
"GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory = Adel_output)",
"index=False) del plot_df, Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene:",
"in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file",
"TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df,",
"# camera above the canopy # Green fraction if GF: Azimuth = [0]",
"= cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width = 2000, relative_height =",
"2000, relative_height = relative_height, output_directory = Adel_output) # Simulate BRDF (need large scene)",
"density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars =",
"relative_height, output_directory = Adel_output) if TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye",
"import povray_Green from pyDOE import * from scipy.stats import uniform from openalea.core.path import",
"relative_height, output_directory = Adel_output) # Simulate BRDF (need large scene) if Multi_spectral: #",
"in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel # Save",
"= float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2,",
"nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0]",
"Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals():",
"sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'],",
"from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output,",
"image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory",
"dep = float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length) del",
"fov_fisheye = [120] dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area",
"New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new,",
"Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output,",
"a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1",
"new_plot_df del Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output",
"= float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 =",
"to conduct phenotyping experiments 11/09/2017 <NAME> ''' import os from adel import AdelR",
"povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width = 2000,",
"+ '/' + name_canopy, 'BGEOM') # Green fraction if GF: sampling_times = GF_camera['Times_sampling']",
"Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501) R = RT[:,0] T =",
"= []): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort =",
"fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal",
"Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera,",
"'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern table to interpolate the",
"image_width = 2000, relative_height = relative_height, output_directory = Adel_output) # Simulate BRDF (need",
"= cameras_fisheye, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory =",
"pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye =",
"sim_width = 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort =",
"from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple,",
"7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width =",
"[0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width = 12.0 sampling_times = 7",
"GF_camera['distance'], z_top = 0, output_directory = Adel_output) if 'result_df' in locals(): result_df =",
"if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output)",
"development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel =",
"Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF",
"name_canopy, 'BGEOM') # Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain,",
"povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in",
"generate three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01,",
"dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df'",
"float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf",
"del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new",
"devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']),",
"for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye = [120]",
"Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind =",
"try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0",
"'/' + name_canopy, 'BGEOM') # Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras",
"canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain = New_domain del",
"Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants,",
"float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length) del Param, development_parameters,",
"number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2",
"Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501) R =",
"Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file):",
"AdelR from adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas",
"try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0",
"import plantgen_interface import numpy as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import",
"domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT)",
"plot_df, Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output +",
"= range(400, 2501) R = RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']:",
"RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown =",
"if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith",
"from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind",
"duplicate = 20, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars,",
"= float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length) del Param,",
"= cameras, image_height = 1000, image_width = 1000, relative_height = relative_height, z_top =",
"in locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for FAPAR",
"Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref,",
"domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it and move forward!!!***' result_df_path",
"GF = False, GF_camera = [], FAPAR = False, Sunlit_TT = [], Sunlit_Ang",
"2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6,",
"= 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']),",
"path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path,",
"wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical,",
"and move forward!!!***' result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT,",
"= Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel",
"name_canopy, 'BGEOM') # Common setting relative_height = 200 # camera above the canopy",
"z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width = 2000, relative_height = relative_height,",
"Ind, cameras = cameras, image_height = 1000, image_width = 1000, relative_height = relative_height,",
"= dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants",
"GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing =",
"New_domain, output_directory = Adel_output, thermal = TT, Ind = Ind) del New_canopy povray_image_fisheye",
"import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import",
"Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters =",
"name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green",
"= wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin",
"= Adel_output) if TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh",
"from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM,",
"Azimuth = [0] fov = [10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times,",
"= new_plot_df del Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene:",
"Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals,",
"= float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length =",
"= dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants =",
"= True, GF = True, Multi_spectral = False, save_scene = False): try: #",
"# Setting of prosail RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car",
"Sunlit_Ang = [], Multi_spectral = False, Ray_camera = [], Ray_light = []): try:",
"Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras =",
"fraction if GF: Azimuth = [0] fov = [10] sampling_times = 4 cameras",
"domain, output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, result_df =",
"Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new,",
"[] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera",
"''' import os from adel import AdelR from adel.geometric_elements import Leaves from adel.AdelR",
"0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build",
"+ '/' + name_canopy, 'BGEOM') # Common setting relative_height = 200 # camera",
"large scene) if Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n = Param['N'],",
"Setting of prosail RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car =",
"R = RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave,",
"output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh,",
"plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from",
"from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from",
"in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path",
"Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2.",
"Ray_camera = [], Zenith_GF = [], FAPAR = True, GF = True, Multi_spectral",
"for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave,",
"= Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel,",
"Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light,",
"RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref =",
"'%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye",
"float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort",
"inter_row = Row_spacing, width = sim_width, length = dup_length) del Param, development_parameters, wheat_leaves",
"Ind = Ind, cameras = cameras, image_height = 1000, image_width = 1000, relative_height",
"Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory",
"n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2",
"= range(400, 2501) R = RT[:,0] T = RT[:,1] for wave in Waves_camera:",
"Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print",
"= z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width = 2000, relative_height =",
"[], Ray_camera = [], Zenith_GF = [], FAPAR = True, GF = True,",
"Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF = [],",
"= float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 =",
"Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene",
"pd from adel.plantgen import plantgen_interface import numpy as np from adel.astk_interface import AdelWheat",
"1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern table to interpolate",
"save_scene = False): try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0",
"FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times = 7 dup_width",
"plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output,",
"cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene,",
"R = RT[:,0] T = RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave,",
"= 20, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT",
"True} # build the distribution pattern table to interpolate the density Wheat_Adel =",
"wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path,",
"adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param,",
"import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun",
"= GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory = Adel_output) if 'result_df'",
"thermals, Canopy, Adel_output, LAI = False,save_scene = False, GF = False, GF_camera =",
"= float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2 =",
"= GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal =",
"nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing)",
"import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI =",
"brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'],",
"= float(Param['Density']), duplicate = 40, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars",
"Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry",
"= A_sun, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory =",
"plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area,",
"[10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh,",
"= Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind,",
"del plot_df, Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output",
"LAI = False,save_scene = False, GF = False, GF_camera = [], FAPAR =",
"Row_spacing, width = sim_width, length = dup_length) del Param, development_parameters, wheat_leaves domain =",
"float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width",
"= Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw =",
"= True, Multi_spectral = False, save_scene = False): try: # Adel parameters Row_spacing",
"= Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if",
"Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene =",
"from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def",
"float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length) del development_parameters, wheat_leaves",
"the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40, devT = development_parameters,",
"= cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top =",
"z_top = z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width = 2000, relative_height",
"relative_height = relative_height, output_directory = Adel_output) # Simulate BRDF (need large scene) if",
"scene) if Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n = Param['N'], cab",
"LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals():",
"TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2",
"from pyDOE import * from scipy.stats import uniform from openalea.core.path import path from",
"= [], FAPAR = True, GF = True, Multi_spectral = False, save_scene =",
"output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh,",
"canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye =",
"TT, Ind = Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'],",
"cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0,",
"= new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye =",
"= Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel,",
"Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0",
"cameras_fisheye, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output)",
"# Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times",
"0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0,",
"cameras = cameras, image_height = 1000, image_width = 1000, relative_height = relative_height, z_top",
"parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation",
"path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry file name_canopy =",
"Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal",
"Canopy, Adel_output, LAI = False,save_scene = False, GF = False, GF_camera = [],",
"* from scipy.stats import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves,",
"= povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass",
"= plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False)",
"dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times,",
"= sim_width, Row_spacing = Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain,",
"it and move forward!!!***' result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind,",
"wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration':",
"sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye,",
"= float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves =",
"= plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df =",
"= Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain,",
"development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation =",
"= relative_height, output_directory = Adel_output) # Simulate BRDF (need large scene) if Multi_spectral:",
"Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT,",
"float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density']))",
"n0 = float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1",
"from adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as",
"Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye =",
"12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width =",
"RT[:,0] T = RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R,",
"'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern",
"not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'],",
"= path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye =",
"A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras =",
"car = Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave",
"= 200 # camera above the canopy # Green fraction if GF: Azimuth",
"the canopy # Green fraction if GF: Azimuth = [0] fov = [10]",
"dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye",
"path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and move forward!!!***' result_df_path",
"GF = True, Multi_spectral = False, save_scene = False): try: # Adel parameters",
"Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError: print 'Pass it and",
"to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20, devT",
"nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df =",
"float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']),",
"configuration sim_width = float(Canopy['width']) # m, generate three rows dup_length = float(Canopy['length']) Row_spacing",
"float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']),",
"from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE",
"axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import * from",
"float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']),",
"TT, Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF = [], FAPAR =",
"return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera = [],",
"'/' + name_canopy, 'BGEOM') # Common setting relative_height = 200 # camera above",
"float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']),",
"as pd from adel.plantgen import plantgen_interface import numpy as np from adel.astk_interface import",
"8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length =",
"float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']),",
"= RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref",
"import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI",
"float(Param['Density']), duplicate = 40, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars =",
"result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light =",
"GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT,",
"float(Param['Density']), duplicate = 20, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars =",
"# Green fraction if GF: Azimuth = [0] fov = [10] sampling_times =",
"FAPAR = False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral = False, Ray_camera",
"cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing,",
"= GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene,",
"20, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT =",
"= [120] dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area =",
"result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye",
"float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01,",
"float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing,",
"'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon':",
"del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants",
"Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth =",
"= Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output)",
"Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height",
"[], FAPAR = False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral = False,",
"= float(Param['n1']), n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 =",
"domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals:",
"prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal,",
"sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box,",
"run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']),",
"True, Multi_spectral = False, save_scene = False): try: # Adel parameters Row_spacing =",
"thermal = TT, Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new,",
"+ name_canopy, 'BGEOM') # Common setting relative_height = 200 # camera above the",
"m, generate three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink':",
"dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 =",
"= 2000, relative_height = relative_height, output_directory = Adel_output) if TT in Sunlit_TT: for",
"T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh,",
"sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing,",
"development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT",
"plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common setting relative_height = 200 #",
"R_xydb, R_srdb, genGeoLeaf import pandas as pd from adel.plantgen import plantgen_interface import numpy",
"Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times = 7 dup_width = 8.0 New_canopy,",
"print 'Pass it and move forward!!!***' result_df_path = [] pass return Adel_output def",
"= TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT,",
"import R_xydb, R_srdb, genGeoLeaf import pandas as pd from adel.plantgen import plantgen_interface import",
"Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new,",
"= z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width =",
"Simulate BRDF (need large scene) if Multi_spectral: # Setting of prosail RT =",
"image_height = 1000, image_width = 1000, relative_height = relative_height, z_top = z_top, output_directory",
"output_directory = Adel_output) if TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye =",
"'%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and move forward!!!***' result_df_path =",
"run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep",
"= AdelWheat(density = float(Param['Density']), duplicate = 40, devT = development_parameters, leaves = wheat_leaves,",
"= z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye",
"= float(Canopy['width']) # m, generate three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing'])",
"Adel_output, thermal = TT, Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh =",
"False,save_scene = False, GF = False, GF_camera = [], FAPAR = False, Sunlit_TT",
"float(Canopy['width']) # m, generate three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars",
"image_width = 1000, relative_height = relative_height, z_top = z_top, output_directory = Adel_output) result_df_path",
"wave=wave, dict=Adel_output) except TypeError: print 'Pass it and move forward!!!***' result_df_path = []",
"sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants,",
"geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM')",
"save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common setting relative_height = 200",
"Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, result_df",
"FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width",
"TypeError: print 'Pass it and move forward!!!***' result_df_path = [] pass return Adel_output",
"development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM =",
"= dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) del plantgl_scene",
"set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output,",
"save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green fraction if GF: sampling_times",
"= run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep =",
"povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv')))",
"result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras = cameras,",
"Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if",
"result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye =",
"import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as pd from",
"import AdelR from adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import",
"Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top =",
"above the canopy # Green fraction if GF: Azimuth = [0] fov =",
"= Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width'])",
"as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import",
"camera above the canopy # Green fraction if GF: Azimuth = [0] fov",
"LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df'",
"[0] fov = [10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF,",
"Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene = False, GF = False,",
"Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory",
"= sim_width, length = dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area =",
"main function to conduct phenotyping experiments 11/09/2017 <NAME> ''' import os from adel",
"float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern table to interpolate the density",
"Ind, thermals, Canopy, Adel_output, LAI = False,save_scene = False, GF = False, GF_camera",
"False, Ray_camera = [], Ray_light = []): try: # Adel parameters development_parameters =",
"sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0]",
"genGeoLeaf import pandas as pd from adel.plantgen import plantgen_interface import numpy as np",
"Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output,",
"density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40, devT = development_parameters, leaves",
"1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution pattern table",
"if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel",
"= Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False)",
"= TT, Ind = Ind, cameras = cameras, image_height = 1000, image_width =",
"= TT, Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top",
"float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']),",
"Ray_camera = [], Ray_light = []): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential",
"fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT,",
"= RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave,",
"= float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers =",
"2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) if TT in",
"adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI",
"from adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB",
"= 2000, relative_height = relative_height, output_directory = Adel_output) # Simulate BRDF (need large",
"os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output)",
"= TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT,",
"Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light,",
"= development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM",
"Adel_output, thermal = TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal",
"Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df #",
"Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if",
"adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter,",
"float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2,",
"canopy configuration sim_width = float(Canopy['width']) # m, generate three rows dup_length = float(Canopy['length'])",
"plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import * from scipy.stats import",
"False, GF_camera = [], FAPAR = False, Sunlit_TT = [], Sunlit_Ang = [],",
"set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene",
"= False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral = False, Ray_camera =",
"Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras",
"inter_row = Row_spacing, width = sim_width, length = dup_length) del development_parameters, wheat_leaves domain",
"= False, GF_camera = [], FAPAR = False, Sunlit_TT = [], Sunlit_Ang =",
"cameras, image_height = 1000, image_width = 1000, relative_height = relative_height, z_top = z_top,",
"povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT, Ind =",
"GF: Azimuth = [0] fov = [10] sampling_times = 4 cameras = Sampling_GF(domain,",
"relative_height = 200 # camera above the canopy # Green fraction if GF:",
"Row_spacing = Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye,",
"dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants =",
"os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except TypeError:",
"density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy",
"plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if",
"Ind, TT, Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF = [], FAPAR",
"= Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras",
"Ray_light = [], Ray_camera = [], Zenith_GF = [], FAPAR = True, GF",
"cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy,",
"TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top",
"= float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) # m, generate three rows",
"from adel.plantgen import plantgen_interface import numpy as np from adel.astk_interface import AdelWheat from",
"New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height",
"A_sun = A_sun, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory",
"output_directory = Adel_output, thermal = TT, Ind = Ind) del New_canopy povray_image_fisheye =",
"adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray",
"result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and move",
"pattern table to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate =",
"for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras",
"path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from",
"dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type",
"in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI:",
"'%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False)",
"'%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green fraction if",
"povfile_box, thermal = TT, Ind = Ind, cameras = cameras, image_height = 1000,",
"domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref,",
"= 1000, relative_height = relative_height, z_top = z_top, output_directory = Adel_output) result_df_path =",
"Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential =",
"= float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']),",
"= [], Ray_light = []): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential =",
"= Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory =",
"cameras = cameras_fisheye, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory",
"duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing =",
"relative_height = relative_height, z_top = z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv')))",
"# canopy configuration sim_width = float(Canopy['width']) # m, generate three rows dup_length =",
"Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT, Ind = Ind) del New_canopy",
"dict=Adel_output) except TypeError: print 'Pass it and move forward!!!***' result_df_path = [] pass",
"= povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width =",
"Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df =",
"Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras = cameras, image_height =",
"soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,",
"if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times = 7 dup_width =",
"Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF",
"N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density",
"[], Multi_spectral = False, Ray_camera = [], Ray_light = []): try: # Adel",
"pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel # Save geometry file name_canopy =",
"Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal =",
"= Adel_output, thermal = TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box,",
"[0] sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene,",
"float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2,",
"= [0] fov_fisheye = [120] dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants,",
"brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not",
"adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf import pandas as pd",
"the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20, devT = development_parameters,",
"domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df",
"12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation",
"width = sim_width, length = dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain",
"False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral = False, Ray_camera = [],",
"'%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT)",
"= 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length",
"Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path",
"Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/'",
"soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type = Param['soil_type'], dict=Adel_output) if 'plot_df' in locals(): result_plot_path =",
"200 # camera above the canopy # Green fraction if GF: Azimuth =",
"AdelWheat(density = float(Param['Density']), duplicate = 20, devT = development_parameters, leaves = wheat_leaves, pattern='regular',",
"= sim_width, length = dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area",
"The main function to conduct phenotyping experiments 11/09/2017 <NAME> ''' import os from",
"cameras = cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top",
"z_top = z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) #",
"Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height = GF_camera['distance'],",
"file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') #",
"= False, GF = False, GF_camera = [], FAPAR = False, Sunlit_TT =",
"canopy # Green fraction if GF: Azimuth = [0] fov = [10] sampling_times",
"setting relative_height = 200 # camera above the canopy # Green fraction if",
"n2 = float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1",
"in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye,",
"float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars",
"= [0] fov = [10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth,",
"= '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common setting",
"povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height =",
"dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants,",
"domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel",
"if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye",
"name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Common",
"[], Zenith_GF = [], FAPAR = True, GF = True, Multi_spectral = False,",
"'BGEOM') # Green fraction if GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times,",
"Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height = 2000, image_width",
"R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain,",
"domain, output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, new_df =",
"np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple,",
"width = sim_width, length = dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area",
"T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T)",
"output_directory = Adel_output) # Simulate BRDF (need large scene) if Multi_spectral: # Setting",
"Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF = [], FAPAR = True,",
"float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) #",
"build the distribution pattern table to interpolate the density Wheat_Adel = AdelWheat(density =",
"if Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n = Param['N'], cab =",
"TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if",
"= AdelWheat(density = float(Param['Density']), duplicate = 20, devT = development_parameters, leaves = wheat_leaves,",
"not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) except",
"= Row_spacing, width = sim_width, length = dup_length) del development_parameters, wheat_leaves domain =",
"'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller':",
"= 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width",
"float(Param['n2']), number_tillers = float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']),",
"del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye,",
"soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave,",
"plantgen_interface import numpy as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas",
"= float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration",
"duplicate = 40, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars,",
"# Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind)",
"= float(Param['number_tillers']), Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 =",
"= float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg =",
"Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'],",
"GF: sampling_times = GF_camera['Times_sampling'] cameras = Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith =",
"in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it",
"1.0 dup_length = 12.0 development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0",
"# Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path =",
"else: plot_df = new_plot_df del Canopy_Adel # Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT)",
"40, devT = development_parameters, leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT =",
"Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if",
"from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind",
"if TT in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new,",
"Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene, new_df",
"= povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file",
"= Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height =",
"= 7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width",
"Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'],",
"cab = Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm",
"from scipy.stats import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development",
"adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import",
"depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length",
"GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain,",
"= 0, output_directory = Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else:",
"Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT,",
"# Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' +",
"Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file =",
"wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width =",
"Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file):",
"relative_height = GF_camera['distance'], z_top = 0, output_directory = Adel_output) if 'result_df' in locals():",
"range(400, 2501) R = RT[:,0] T = RT[:,1] for wave in Ray_camera['Waves']: Plant_optical",
"# Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye",
"= Adel_output) if 'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df",
"GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top",
"dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width,",
"= False, save_scene = False): try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width",
"thermal = TT, Ind = Ind, cameras = cameras, image_height = 1000, image_width",
"openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import",
"Adel_output, LAI = False,save_scene = False, GF = False, GF_camera = [], FAPAR",
"= pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye",
"run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col':",
"New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width",
"import pandas as pd from adel.plantgen import plantgen_interface import numpy as np from",
"= [], FAPAR = False, Sunlit_TT = [], Sunlit_Ang = [], Multi_spectral =",
"= sim_width, Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye,",
"<NAME> ''' import os from adel import AdelR from adel.geometric_elements import Leaves from",
"povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind =",
"three rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration':",
"adel.macro.povray_pixels_several_colors import set_color_metamers_organs from adel.povray.FAPAR import Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import",
"Ray_light = []): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort",
"= 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top",
"= 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) # Simulate",
"= Row_spacing, width = sim_width, length = dup_length) del Param, development_parameters, wheat_leaves domain",
"= Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT, Ind = Ind) del",
"leaves = wheat_leaves, pattern='regular', run_adel_pars = run_adel_pars, incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']),",
"= float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length) del development_parameters,",
"output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR",
"adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from adel.ADEL_OPT.Adel_OPT_Ind import plot_LAI from adel.macro.povray_pixels_several_colors import",
"dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene, wave=wave,",
"'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass",
"Row_spacing = Row_spacing) del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0]",
"Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output,",
"in Sunlit_TT: for A_sun in Sunlit_Ang: povray_image_fisheye = Hemispherical_IM_Sun(povfile_mesh = povfile_mesh_new, z_top =",
"cbrown = Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave = range(400, 2501)",
"= prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'],",
"= [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [],",
"AdelWheat(density = float(Param['Density']), duplicate = 40, devT = development_parameters, leaves = wheat_leaves, pattern='regular',",
"float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) # canopy configuration sim_width = float(Canopy['width']) # m, generate",
"= Wheat_Adel.nplants for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] #",
"2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) # Simulate BRDF",
"z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind = Ind)",
"povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras =",
"the distribution pattern table to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']),",
"length = dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants",
"= Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, image_height = 2000,",
"= set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants,",
"conduct phenotyping experiments 11/09/2017 <NAME> ''' import os from adel import AdelR from",
"domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene =",
"= [0] Zenith_fisheye = [0] sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants,",
"thermal = TT, Ind = Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal =",
"Zenith_fisheye = [0] fov_fisheye = [120] dup_width = 12.0 sampling_times = 7 New_canopy,",
"import get_exposed_areas from adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green",
"Adel_output, Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df",
"wave in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness'])",
"TT, Ind = Ind, cameras = cameras, image_height = 1000, image_width = 1000,",
"table to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20,",
"Save geometry file name_canopy = '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy,",
"= [], Multi_spectral = False, Ray_camera = [], Ray_light = []): try: #",
"set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path",
"[0] fov_fisheye = [120] dup_width = 12.0 sampling_times = 7 New_canopy, New_nplants, New_domain,",
"if GF: Azimuth = [0] fov = [10] sampling_times = 4 cameras =",
"Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal",
"wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain, povfile_scene=povfile_scene,",
"scipy.stats import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import",
"Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal =",
"dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2.",
"Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for FAPAR if FAPAR:",
"RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref =",
"= [0] sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area =",
"= 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) if TT",
"adel.postprocessing import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import",
"Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']),",
"fov)[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT,",
"locals(): plot_df = pd.concat([plot_df,new_plot_df]) else: plot_df = new_plot_df del Canopy_Adel # Save geometry",
"image_width = GF_camera['image_width'], relative_height = GF_camera['distance'], z_top = 0, output_directory = Adel_output) if",
"False, GF = False, GF_camera = [], FAPAR = False, Sunlit_TT = [],",
"= [], Sunlit_Ang = [], Multi_spectral = False, Ray_camera = [], Ray_light =",
"dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants",
"wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT)",
"= relative_height, output_directory = Adel_output) if TT in Sunlit_TT: for A_sun in Sunlit_Ang:",
"'BGEOM') # Common setting relative_height = 200 # camera above the canopy #",
"= povfile_mesh_new, z_top = z_top_new, cameras = cameras_fisheye, A_sun = A_sun, image_height =",
"Row_spacing, width = sim_width, length = dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain",
"Zenith_GF = [], FAPAR = True, GF = True, Multi_spectral = False, save_scene",
"if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave,soil_type =",
"index=False) # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0]",
"Sampling_diagnal, Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene,",
"True, GF = True, Multi_spectral = False, save_scene = False): try: # Adel",
"interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20, devT =",
"[], FAPAR = True, GF = True, Multi_spectral = False, save_scene = False):",
"= dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain =",
"Hemispherical_IM, Sampling_GF, Hemispherical_IM_Sun from adel.povray.GF_RGB import Green_Fract, Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy,",
"TT, Ind = Ind) del New_canopy povray_image_fisheye = Hemispherical_IM(povfile_mesh = povfile_mesh_new, z_top =",
"1000, image_width = 1000, relative_height = relative_height, z_top = z_top, output_directory = Adel_output)",
"from adel import AdelR from adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb,",
"= set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind)",
"sim_width, length = dup_length) del development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area",
"= [], Ray_camera = [], Zenith_GF = [], FAPAR = True, GF =",
"sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory =",
"relative_height, z_top = z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False)",
"= dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain = New_domain del plantgl_scene",
"Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in thermals: Canopy_Adel =",
"for TT in thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI",
"Zenith_fisheye = [0] sampling_times = 7 dup_width = 8.0 New_canopy, New_nplants, New_domain, New_area",
"BRDF (need large scene) if Multi_spectral: # Setting of prosail RT = prosail.prospect_5b(n",
"= '%s%s%s%s.bgeom'%('Ind_',Ind,'_TT_',TT) if save_scene: plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green fraction",
"in Ray_camera['Waves']: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file",
"numpy as np from adel.astk_interface import AdelWheat from adel.stand.Generate_canopy import get_exposed_areas from adel.postprocessing",
"dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf':",
"False, save_scene = False): try: # Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width =",
"Ind = Ind, cameras = cameras, image_height = GF_camera['image_height'], image_width = GF_camera['image_width'], relative_height",
"prosail RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown",
"11/09/2017 <NAME> ''' import os from adel import AdelR from adel.geometric_elements import Leaves",
"Azimuth_fisheye = [0] Zenith_fisheye = [0] fov_fisheye = [120] dup_width = 12.0 sampling_times",
"0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1,",
"= Param['Car'], cbrown = Param['Cbrown'], cw = Param['Cw'], cm = Param['Cm']) Full_wave =",
"Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output,",
"Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type =",
"domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del",
"= Adel_development(N_phytomer_potential = float(Param['N_leaf']), a_cohort = float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']),",
"Multi_spectral = False, save_scene = False): try: # Adel parameters Row_spacing = float(Param['Row_spacing'])",
"LAI plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv')))",
"'result_df' in locals(): result_df = pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for",
"0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']), 'drop_empty': True} # build the distribution",
"image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output) if",
"'fracLeaf': 0.2, 'stemDuration': 2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller':",
"= New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new,",
"plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new =",
"sim_width, Row_spacing = Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times,",
"new_df # Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0]",
"float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width, length = dup_length)",
"float(Param['a_cohort']), TT_hs_0 = float(Param['T_cohort']), TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']),",
"= float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row =",
"A_sun, image_height = 2000, image_width = 2000, relative_height = relative_height, output_directory = Adel_output)",
"uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind import Adel_Leaves, Adel_development import prosail from",
"# Adel parameters Row_spacing = float(Param['Row_spacing']) sim_width = 1.0 dup_length = 12.0 development_parameters",
"7 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length =",
"''' The main function to conduct phenotyping experiments 11/09/2017 <NAME> ''' import os",
"fov = [10] sampling_times = 4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing,",
"experiments 11/09/2017 <NAME> ''' import os from adel import AdelR from adel.geometric_elements import",
"povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain, output_directory = Adel_output, thermal = TT, Ind",
"= Wheat_Adel.nplants Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) del Wheat_Adel plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI",
"= float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2, 'fracLeaf': 0.2, 'stemDuration': 2. /",
"plantgl_scene.save(Adel_output + '/' + name_canopy, 'BGEOM') # Green fraction if GF: sampling_times =",
"= Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0] povfile_mesh_new, povfile_box_new, z_top_new = Pov_Scene(New_canopy, New_domain,",
"= Pov_Scene(plantgl_scene, domain, output_directory = Adel_output, thermal = TT, Ind = Ind) povfile_scene,",
"import axis_statistics_simple, plot_statistics_simple, plot_statistics_simple_filter, axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import *",
"from adel.povray.povray_ind import povray_Green from pyDOE import * from scipy.stats import uniform from",
"Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy, Adel_output, LAI = False,save_scene = False,",
"sim_width = sim_width, Row_spacing = Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye =",
"Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind =",
"R_srdb, genGeoLeaf import pandas as pd from adel.plantgen import plantgen_interface import numpy as",
"povfile_scene=povfile_scene, wave=wave, dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=New_domain,",
"# build the distribution pattern table to interpolate the density Wheat_Adel = AdelWheat(density",
"adel import AdelR from adel.geometric_elements import Leaves from adel.AdelR import R_xydb, R_srdb, genGeoLeaf",
"'Pass it and move forward!!!***' result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param,",
"New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length,",
"= duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width, Row_spacing",
"R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness']) Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain,",
"Common setting relative_height = 200 # camera above the canopy # Green fraction",
"plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in locals(): plot_df = pd.concat([plot_df,new_plot_df])",
"pandas as pd from adel.plantgen import plantgen_interface import numpy as np from adel.astk_interface",
"incT = float(Param['Deta_Incl_Tiller']), ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row",
"= Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf'])) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2,",
"pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera =",
"result_plot_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('plot_LAI_',Ind,'_TT_',TT,'.csv'))) plot_df.to_csv(result_plot_path, index=False) del plot_df, Canopy_Adel # Save geometry file",
"axis_statistics_simple_filter from adel.povray.povray_ind import povray_Green from pyDOE import * from scipy.stats import uniform",
"Row_spacing = Row_spacing, fov = GF_camera['fov'])[0] povfile_mesh, povfile_box, z_top = Pov_Scene(plantgl_scene, domain, output_directory",
"Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file = povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh,",
"Pov_Scene from adel.povray.Canray import duplicate_scene, Optical_canopy, Optical_soil, povray_RF def Phenotyping_Wheat(Param, Ind, thermals, Canopy,",
"Fisheye for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times =",
"# Simulate BRDF (need large scene) if Multi_spectral: # Setting of prosail RT",
"if LAI: new_plot_df = plot_LAI(Canopy_Adel, TT, domain_area, nplants, Adel_output, Ind) if 'plot_df' in",
"prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car = Param['Car'], cbrown = Param['Cbrown'], cw",
"z_top, output_directory = Adel_output) result_df_path = path(os.path.join(Adel_output, '%s%s%s%s%s'%('Fraction_',Ind,'_TT_',TT,'.csv'))) result_df.to_csv(result_df_path, index=False) # Fisheye for",
"result_df = pd.concat([result_df,new_df]) else: result_df = new_df # Fisheye for FAPAR if FAPAR:",
"= RT[:,0] T = RT[:,1] for wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave,",
"sim_width = float(Canopy['width']) # m, generate three rows dup_length = float(Canopy['length']) Row_spacing =",
"4 cameras = Sampling_GF(domain, sampling_times, Azimuth, Zenith_GF, Row_spacing, fov)[0] povfile_mesh, povfile_box, z_top =",
"to interpolate the density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 40, devT",
"for FAPAR if FAPAR: Azimuth_fisheye = [0] Zenith_fisheye = [0] sampling_times = 7",
"TT_flag_ligulation = float(Param['TT_flag_ligulation']), n0 = float(Param['n0']), n1 = float(Param['n1']), n2 = float(Param['n2']), number_tillers",
"2. / 1.2, 'dHS_col': 0.2, 'dHS_en': 0, 'epsillon': 1e-6, 'HSstart_inclination_tiller': 1, 'rate_inclination_tiller': float(Param['rate_Tiller']),",
"thermals: Canopy_Adel = Wheat_Adel.setup_canopy(age=TT) plantgl_scene = set_color_metamers_organs(Canopy_Adel)[0] # Summary LAI if LAI: new_plot_df",
"New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width = sim_width,",
"wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area nplants = Wheat_Adel.nplants for TT in",
"pyDOE import * from scipy.stats import uniform from openalea.core.path import path from adel.ADEL_OPT.Adel_OPT_Ind",
"cameras_fisheye, A_sun = A_sun, image_height = 2000, image_width = 2000, relative_height = relative_height,",
"'drop_empty': True} # build the distribution pattern table to interpolate the density Wheat_Adel",
"def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light = [], Ray_camera = [], Zenith_GF =",
"wave in Waves_camera: Plant_optical = Optical_canopy(wave=wave, Full_wave=Full_wave, R=R, T=T) soil_ref = Optical_soil(wave, brightness=Param['brightness'])",
"soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if not os.path.exists(Output_file): Output_file =",
"float(Param['incl1']), incl2 = float(Param['incl2']), N_elg = float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline",
"thermal = TT, Ind = Ind) povfile_scene, new_df = Green_Fract(povfile_mesh, povfile_box, thermal =",
"= 8.0 New_canopy, New_nplants, New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length",
"of prosail RT = prosail.prospect_5b(n = Param['N'], cab = Param['Cab'], car = Param['Car'],",
"result_df.to_csv(result_df_path, index=False) except TypeError: print 'Pass it and move forward!!!***' result_df_path = []",
"Lamina_L1 = float(Param['Lamina_L1']), N2 = float(Param['N2']), incl1 = float(Param['incl1']), incl2 = float(Param['incl2']), N_elg",
"length = dup_length) del Param, development_parameters, wheat_leaves domain = Wheat_Adel.domain domain_area = Wheat_Adel.domain_area",
"New_domain, New_area = duplicate_scene(plantgl_scene, nplants, canopy_width = dup_width, canopy_length = dup_length, sim_width =",
"plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path = path(os.path.join(Adel_output, '%s%s%s'%('Fraction_',Ind,'.csv'))) result_df.to_csv(result_df_path, index=False) except",
"domain = New_domain del plantgl_scene cameras_fisheye = Sampling_diagnal(New_domain, sampling_times, Azimuth_fisheye, Zenith_fisheye, Row_spacing, fov_fisheye)[0]",
"density Wheat_Adel = AdelWheat(density = float(Param['Density']), duplicate = 20, devT = development_parameters, leaves",
"= povray_RF(Ray_light=Ray_light, Ray_camera=Ray_camera, Plant_optical=Plant_optical, soil_ref=soil_ref, domain=domain, povfile_scene=povfile_mesh, wave=wave, soil_type = Param['soil_type'], dict=Adel_output) if",
"forward!!!***' result_df_path = [] pass return Adel_output def Phenotyping_Wheat_TT(Param, Ind, TT, Adel_output, Ray_light",
"= 1000, image_width = 1000, relative_height = relative_height, z_top = z_top, output_directory =",
"[], Ray_light = []): try: # Adel parameters development_parameters = Adel_development(N_phytomer_potential = float(Param['N_leaf']),",
"= float(Param['N_elg']), density = float(Param['Density'])) wheat_leaves = Adel_Leaves(incline = float(Param['incl_leaf']), dev_Az_Leaf = float(Param['dev_Az_Leaf']))",
"rows dup_length = float(Canopy['length']) Row_spacing = float(Param['Row_spacing']) run_adel_pars = {'senescence_leaf_shrink': 0.01, 'leafDuration': 2,",
"float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width = sim_width,",
"= Sampling_GF(domain, sampling_times, Azimuth = GF_camera['azimuth'], Zenith = GF_camera['zenith'], Row_spacing = Row_spacing, fov",
"locals(): result_plot_path = path(os.path.join(Adel_output, '%s%s%s'%('plot_LAI_',Ind,'.csv'))) plot_df.to_csv(result_plot_path, index=False) if 'result_df' in locals(): result_df_path =",
"dup_length, sim_width = sim_width, Row_spacing = Row_spacing) domain = New_domain del plantgl_scene cameras_fisheye",
"Ind) povfile_scene, result_df = Green_Fract(povfile_mesh, povfile_box, thermal = TT, Ind = Ind, cameras",
"ibmM = float(Param['incl_main']), depMin = float(Param['min_Tiller']), dep = float(Param['max_Tiller']), inter_row = Row_spacing, width",
"Multi_spectral = False, Ray_camera = [], Ray_light = []): try: # Adel parameters"
] |
[
"@commands.command() async def clean(self, ctx, num : int): await ctx.channel.purge(limit = num+1) def",
"class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num : int): await ctx.channel.purge(limit =",
"Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num : int): await ctx.channel.purge(limit = num+1)",
"def clean(self, ctx, num : int): await ctx.channel.purge(limit = num+1) def setup(bot): bot.add_cog(Moderations(bot))",
"import discord from discord.ext import commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command()",
"from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num :",
"Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num : int): await ctx.channel.purge(limit",
"import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num : int): await",
"import commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx,",
"from discord.ext import commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def",
"discord from discord.ext import commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async",
"async def clean(self, ctx, num : int): await ctx.channel.purge(limit = num+1) def setup(bot):",
"commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num",
"<reponame>james10949/sijingprogram<gh_stars>0 import discord from discord.ext import commands from core.classes import Cog_Extension class Moderations(Cog_Extension):",
"core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self, ctx, num : int):",
"discord.ext import commands from core.classes import Cog_Extension class Moderations(Cog_Extension): @commands.command() async def clean(self,"
] |
[
"ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({ 'pane_type': IdMenuPaneNames.otherinfo, }) return",
"padinfo.pane_names import IdMenuPaneNames from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret =",
"import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({ 'pane_type': IdMenuPaneNames.otherinfo, })",
"from padinfo.pane_names import IdMenuPaneNames from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret",
"IdMenuPaneNames from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({",
"class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({ 'pane_type': IdMenuPaneNames.otherinfo, }) return ret",
"padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({ 'pane_type': IdMenuPaneNames.otherinfo,",
"from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize() ret.update({ 'pane_type':",
"import IdMenuPaneNames from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self): ret = super().serialize()",
"<reponame>chasehult/padbot-cogs<gh_stars>0 from padinfo.pane_names import IdMenuPaneNames from padinfo.view_state.base_id import ViewStateBaseId class OtherInfoViewState(ViewStateBaseId): def serialize(self):"
] |
[
"dataset_client.status.commit_id is not None # After committing, the draft will be deleted with",
"test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name)",
"dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number",
"get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name",
"dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2",
"gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client",
"pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert",
"draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client",
"draft 2\") # After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(),",
"with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0]",
"\"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey,",
"dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description",
"gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3)",
"not None # After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(),",
"= get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1",
"1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing, the",
"gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client",
"url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\")",
"description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name)",
"tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError",
"GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError,",
"\"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name()",
"dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\",",
"= dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH,",
"draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name()",
"\"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name()",
"dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft",
"committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts()",
"pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name",
"dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None # After committing, the draft",
"gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\",",
"description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2,",
"\"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description ==",
"gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\")",
"2021 Graviti. Licensed under MIT License. # import pytest from tensorbay.client import GAS",
"\"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey,",
"# Copyright 2021 Graviti. Licensed under MIT License. # import pytest from tensorbay.client",
"# import pytest from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct",
"= dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\")",
"draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number ==",
"Licensed under MIT License. # import pytest from tensorbay.client import GAS from tensorbay.client.gas",
"2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client =",
"import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title",
"draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None",
"test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name)",
"1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError):",
"accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\",",
"get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\")",
"ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url):",
"not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None # After",
"url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\")",
"url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1",
"Copyright 2021 Graviti. Licensed under MIT License. # import pytest from tensorbay.client import",
"= get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client",
"get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name =",
"dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\",",
"DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def",
"draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing,",
"draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\")",
"dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\")",
"get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name =",
"import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url)",
"GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\")",
"dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not",
"dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is",
"gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft",
"is not None # After committing, the draft will be deleted with pytest.raises(TypeError):",
"assert dataset_client.status.commit_id is not None # After committing, the draft will be deleted",
"\"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name()",
"== 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with",
"for draft 2\") # After committing, the draft will be deleted with pytest.raises(TypeError):",
"assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is",
"= get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\",",
"== \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert",
"python3 # # Copyright 2021 Graviti. Licensed under MIT License. # import pytest",
"get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\",",
"\"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self,",
"\"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description",
"class TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name()",
"is None assert dataset_client.status.commit_id is not None # After committing, the draft will",
"\"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3) dataset_client.close_draft(2) with pytest.raises(ResourceNotExistError):",
"None assert dataset_client.status.commit_id is not None # After committing, the draft will be",
"dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3) dataset_client.close_draft(2) with",
"from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from",
"with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url)",
"get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name =",
") with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey,",
"dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description ==",
"draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url):",
"dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None # After committing,",
"== \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client =",
"dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing, the draft",
"\"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] == Draft( draft_number_2,",
"dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with",
"deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert",
"def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client =",
"pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self,",
"be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client =",
"url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\",",
"TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client",
"tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None",
"= dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self,",
"\"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey,",
"= gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\")",
"assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\")",
"is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number",
"<reponame>edsn60/tensorbay-python-sdk #!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. #",
"gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number",
"= get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 =",
"dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\")",
"drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\",",
"assert len(drafts) == 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description",
"import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import",
"tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name,",
"dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\"",
"GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert",
"get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft()",
"= dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing, the draft will be",
"draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client",
"gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\",",
"\"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title",
"url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description",
"assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None #",
"= dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1",
"get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert",
"= get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\")",
"draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing, the draft will",
"tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is",
"2\") # After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\")",
"gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client",
"import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self,",
"dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft =",
"draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2)",
"import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from",
"dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft",
"= GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\")",
"dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(),",
"Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(),",
"draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert",
"= gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert",
"dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey,",
"dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description == \"description01\"",
"draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\",",
"== draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\")",
"for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After",
"== Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError):",
"draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name",
"under MIT License. # import pytest from tensorbay.client import GAS from tensorbay.client.gas import",
"dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 ==",
"get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] == Draft(",
"# After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts",
"from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import",
"dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert",
"dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not",
"url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\")",
"tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title",
"After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def",
"assert draft.title == \"draft-4\" assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft =",
"Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class",
"dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3)",
"== \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name =",
"gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client",
"tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number",
"for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url):",
"StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client",
"url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 =",
"the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert",
"will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client",
"= GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\")",
"dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title ==",
"from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError,",
"tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3) dataset_client.close_draft(2) with pytest.raises(ResourceNotExistError): dataset_client.get_draft(2)",
"draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url):",
"from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client =",
"gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for",
"get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\",",
"accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\")",
"import pytest from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import",
"dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id",
"dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 ==",
"GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\")",
"dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\")",
"assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" )",
"dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3) dataset_client.close_draft(2)",
"draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name",
"pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name",
"with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def",
"= GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\",",
"dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError): dataset_client.get_draft(3) dataset_client.close_draft(2) with pytest.raises(ResourceNotExistError): dataset_client.get_draft(2) gas_client.delete_dataset(dataset_name)",
"drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with",
"test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name)",
"assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number =",
"get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client =",
"the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey,",
"def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client =",
"def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client =",
"DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility",
"# After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name)",
"None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name)",
"None # After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\")",
"pytest from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft",
"#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # import",
"assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url)",
"dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description",
"assert draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title ==",
"draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts)",
"be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1",
"GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\")",
"len(drafts) == 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for",
"== 1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft",
"from tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft:",
"committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self,",
"Graviti. Licensed under MIT License. # import pytest from tensorbay.client import GAS from",
"with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert not dataset_client.status.is_draft assert dataset_client.status.draft_number is None",
"assert dataset_client.status.draft_number is None assert dataset_client.status.commit_id is not None # After committing, the",
"== \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert",
"= gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with pytest.raises(ResourceNotExistError):",
"dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\") dataset_client.close_draft() with",
"dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\", tag=\"V2\") assert",
"deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey,",
"tensorbay.exception import ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def",
"After committing, the draft will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts =",
"assert draft_number_1 == draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url)",
"with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name) def test_commit_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url)",
"dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert",
"gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\")",
"accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) draft_number_1",
"assert draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey, url):",
"\"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\" ) with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-3\") gas_client.delete_dataset(dataset_name)",
".utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey,",
"# # Copyright 2021 Graviti. Licensed under MIT License. # import pytest from",
"= gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for",
"test_close_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name)",
"\"description for draft 1\") dataset_client.commit(\"commit-draft-1\") draft_number_2 = dataset_client.create_draft(\"draft-2\", \"description for draft 2\") #",
"\"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft assert dataset_client.status.draft_number == draft_number_1 assert dataset_client.status.commit_id",
"def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client =",
"= gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError): dataset_client.commit(\"commit-3\", tag=\"V1\") dataset_client.commit(\"commit-3\",",
"\"description for draft 2\") # After committing, the draft will be deleted with",
"def test_update_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client =",
"= get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\") with pytest.raises(ResponseError):",
"url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\") dataset_client.create_draft(\"draft-2\") dataset_client.commit(\"commit-2\", tag=\"V1\") dataset_client.create_draft(\"draft-3\")",
"draft.description == \"description01\" dataset_client.update_draft(2, title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\"",
"\"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert",
"test_create_draft(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name)",
"tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from tensorbay.client.struct import Draft from tensorbay.exception",
"gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\") dataset_client.commit(\"commit-1\", \"test\", tag=\"V1\") dataset_client.create_draft(\"draft-2\") dataset_client.checkout(\"V1\") dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft",
"pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) == 1 assert drafts[0] ==",
"License. # import pytest from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH from",
"will be deleted with pytest.raises(TypeError): get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") drafts = dataset_client.list_drafts() assert len(drafts) ==",
"assert dataset_client.status.commit_id is None with pytest.raises(StatusError): dataset_client.create_draft(\"draft-2\") draft_number = get_draft_number_by_title(dataset_client.list_drafts(), \"draft-1\") assert draft_number_1",
"= GAS(access_key=accesskey, url=url) dataset_name = get_dataset_name() dataset_client = gas_client.create_dataset(dataset_name) dataset_client.create_draft(\"draft-1\", \"description for draft",
"ResourceNotExistError, ResponseError, StatusError from .utility import get_dataset_name, get_draft_number_by_title class TestDraft: def test_create_draft(self, accesskey,",
"dataset_client.create_draft(\"draft-2\", \"description for draft 2\") # After committing, the draft will be deleted",
"1 assert drafts[0] == Draft( draft_number_2, \"draft-2\", DEFAULT_BRANCH, \"OPEN\", \"description for draft 2\"",
"dataset_client.create_branch(\"T123\") dataset_client.create_draft(\"draft-3\", \"description00\") dataset_client.update_draft(title=\"draft-4\", description=\"description01\") draft = dataset_client.get_draft(3) assert draft.title == \"draft-4\" assert",
"title=\"draft-4\", description=\"description02\") draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description == \"description02\"",
"draft = dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def",
"dataset_client.get_draft(2) assert draft.title == \"draft-4\" assert draft.description == \"description02\" gas_client.delete_dataset(dataset_name) def test_close_draft(self, accesskey,",
"== draft_number gas_client.delete_dataset(dataset_name) def test_list_drafts(self, accesskey, url): gas_client = GAS(access_key=accesskey, url=url) dataset_name =",
"MIT License. # import pytest from tensorbay.client import GAS from tensorbay.client.gas import DEFAULT_BRANCH",
"dataset_client = gas_client.create_dataset(dataset_name) draft_number_1 = dataset_client.create_draft(\"draft-1\", \"description\") assert draft_number_1 == 1 assert dataset_client.status.is_draft"
] |
[
"np.int0(box) if i==0 and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox, c,",
"= image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2",
"return bg def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8)",
"if isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image,",
"(1.0 + sigma) * v)) else: lower, upper = cThres_L, cThres_H image =",
"math import imutils import numpy as np import warnings from sklearn.cluster import KMeans",
"2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle",
"streaming, faster computation skeleton = skeletonize(image > 0) else: # upload image mode",
"# plot the relative percentage of each cluster endX = startX + (percent",
"cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font",
"cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1,",
"circularity = 4 * math.pi * (area / (peri*peri)) if circular[0] < circularity",
"pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if",
"= points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3]",
"def reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0]",
"finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours",
"* v)) else: lower, upper = cThres_L, cThres_H image = cv2.Canny(image, lower, upper)",
"thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x,",
"cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font",
"color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)",
"upper = cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if isThin: image =",
"compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w]",
"image, edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO,",
"Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy()",
"cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular,",
"cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx) rect",
"thick==0: thick = -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick)",
"such that it sums to one hist = hist.astype(\"float\") hist /= hist.sum() palette",
"GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0,",
"image.copy(), mask=mask) return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self,",
"3), dtype=\"uint8\") startX = 0 # loop over the percentage of each cluster",
"= (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else:",
"0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle",
"if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy() if",
"= cv2.FONT_ITALIC x, y, w, h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19),",
"= cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0",
"(area / (peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c, i,",
"i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if",
"np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that it sums to one hist",
"rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick = -1 for",
"points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size, pad=3): points",
"filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if kar: return imutils.resize(image,",
"** 2 + (pt2[1] // scale[1] - pt1[1] // scale[1]) ** 2) **",
"+ 2, 0:w * 2 + 3] = (0,0,0) return bg def Color_picker(self,",
"return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask",
"bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h",
"= width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image, text,",
"color, 1) def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L,",
"np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres:",
"contours: for i, shape in enumerate(shapes): if not shape: continue area = cv2.contourArea(c)",
"= cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2:",
"= cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx) ==",
"p3) newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def",
"cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif",
"image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0),",
"import numpy as np import warnings from sklearn.cluster import KMeans from skimage.morphology import",
"detection using the computed median lower = int(max(0, (1.0 - sigma) * v))",
"(0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w * 2 + 3]",
"1000 def dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0] // scale[0]) **",
"arr, res = [], [] while True: cap = cv2.VideoCapture(index) if not cap.read()[0]:",
"= cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index +=",
"one hist = hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\")",
"continue area = cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c, True) approx",
"canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO,",
"thresholding(self, image, auto, lower, max): if auto: _, image = cv2.threshold(image.copy(), 0, 255,",
"cThres_H image = cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image) edge =",
"elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font =",
"= self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy() if isDIL: Dial_K =",
"image_edg, minArea, shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours",
"res = [], [] while True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break",
"import KMeans from skimage.morphology import * from skimage.util import * class OD_CV: def",
"width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag == 4:",
"(255,255,255) bg[0:h * 2 + 3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3]",
"def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin,",
"GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray =",
"== 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif",
"for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image def",
"random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels)",
"wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1),",
"drawText(self, flag, image, text, coords, fontstyle, color, thick, height=None): font = None if",
"(0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3),",
"int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points, color, thick,",
"1) def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H,",
"= cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image) edge = image.copy() if",
"DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag):",
"= self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image =",
"(0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3))",
"area = cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c, True) approx =",
"plot the relative percentage of each cluster endX = startX + (percent *",
"y+10+h+height), color, thick) def drawText(self, flag, image, text, coords, fontstyle, color, thick, height=None):",
"font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle ==",
"return imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit, deci): unit_conv = 1",
"if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self,",
"unit_conv = 1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv = 1000",
"1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2:",
"for c in contours: for i, shape in enumerate(shapes): if not shape: continue",
"0.5 # if flag==1: # rect pts = self.reorder(pts) if flag==1: #rect p1,",
"Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma)",
"= np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if",
"= cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh)",
"def thresholding(self, image, auto, lower, max): if auto: _, image = cv2.threshold(image.copy(), 0,",
"if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font =",
"cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image) edge",
"0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image",
"automatic Canny edge detection using the computed median lower = int(max(0, (1.0 -",
"kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) kernely2 =",
"import * from skimage.util import * class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath)",
"1]]) kernely2 = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) kernels",
"1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0:",
"if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv",
"= pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0], pts[1], pts[3] if",
"points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points,",
"Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge",
"image = cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image) edge = image.copy()",
"cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y, w, h",
"= cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0, 0, 0],",
"image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick): contours, _",
"1], [0, 0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0,",
"== 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif",
"(w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self, flag,",
"= 1 if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv = 10 elif",
"image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3]",
"elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font =",
"(x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size,",
"bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours =",
"h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h =",
"import cv2 import math import imutils import numpy as np import warnings from",
"np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2]",
"cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(),",
"shape in enumerate(shapes): if not shape: continue area = cv2.contourArea(c) if area >",
"if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image,",
"= (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w * 2 +",
"= image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 + 3, w+1:w +",
"None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels =",
"= cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self, image, GK_size, GSigma, DK_size,",
"= np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) kernely2 = np.array([[1,",
"+ (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX =",
"iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return",
"self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size,",
"0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k",
"thick, height=None): font = None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif",
"Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy()",
"if isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy() if",
"flag==1: # rect pts = self.reorder(pts) if flag==1: #rect p1, p2, p3 =",
"rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox)) elif",
"points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size, pad=3): points = self.reorder(points) #",
"= pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1,",
"(0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA)",
"newW = dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1,",
"sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) else: lower,",
"NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)]",
"D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray",
"p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]: newH =",
"area > minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri,",
"-1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])",
"startX = 0 # loop over the percentage of each cluster and the",
"live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx =",
"imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self, flag, pts,",
"= points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h = size",
"kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self, image, pts):",
"= cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6:",
"= KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ =",
"1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1,",
"image = self.thinning(image) edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image",
"// scale[1]) ** 2) ** 0.5 # if flag==1: # rect pts =",
"= dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH,",
"w:w+3] = (255,255,255) bg[0:h * 2 + 3, w+1:w + 2] = (0,0,0)",
"width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color,",
"wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return",
"np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1,",
"def dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0] // scale[0]) ** 2",
"return image def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2:",
"= 0.33 v = np.median(image.copy()) # apply automatic Canny edge detection using the",
"wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self,",
"< 8: continue circularity = 4 * math.pi * (area / (peri*peri)) if",
"p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0], pts[1], pts[3]",
"ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H)",
"4: x, y, w, h = points if width!=0: w = width cv2.rectangle(image,",
"cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3),",
"[w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp =",
"elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2:",
"return cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask",
"elif fontstyle == 7: font = cv2.FONT_ITALIC x, y, w, h = coords",
"0, -1], [1, 0, -1], [1, 0, -1]]) kernels = [kernelx, kernelx2, kernely,",
"unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return",
"200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette",
"dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci)",
"deci): unit_conv = 1 if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv =",
"for i, shape in enumerate(shapes): if not shape: continue area = cv2.contourArea(c) if",
"return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr, res =",
"while True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))",
"** 2) ** 0.5 # if flag==1: # rect pts = self.reorder(pts) if",
"cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box =",
"= np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] =",
"if cAuto: sigma = 0.33 v = np.median(image.copy()) # apply automatic Canny edge",
"fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC",
"1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that it",
"that it sums to one hist = hist.astype(\"float\") hist /= hist.sum() palette =",
"def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image,",
"image def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return",
"> 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if auto:",
"the percentage of each cluster and the color of # each cluster for",
"sigma) * v)) else: lower, upper = cThres_L, cThres_H image = cv2.Canny(image, lower,",
"if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv",
"fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX",
"D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1)",
"prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k))",
"= np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self,",
"imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma",
"[0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad,",
"i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick = -1",
"from sklearn.cluster import KMeans from skimage.morphology import * from skimage.util import * class",
"cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self,",
"thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image,",
"x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif",
"[1, 0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for",
"np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask)",
"contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours:",
"if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index += 1 return",
"percent, color in zip(hist, clt.cluster_centers_): # plot the relative percentage of each cluster",
"thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def",
"(GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1,",
"= cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours: for i,",
"points[1]+points[3]+10), color, thick) elif flag==3: x, y, w, h = points width_Total =",
"4 * math.pi * (area / (peri*peri)) if circular[0] < circularity < circular[1]:",
"isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur",
"# rect pts = self.reorder(pts) if flag==1: #rect p1, p2, p3 = pts[0][0],",
"flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w",
"EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg,",
"cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours: for i, shape",
"h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0]",
"= None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1:",
"1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X),",
"height=None): font = None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle",
"imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1,",
"def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:] =",
"else: p1, p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0]",
"clt.cluster_centers_): # plot the relative percentage of each cluster endX = startX +",
"image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma = 0.33 v =",
"cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img",
"= np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) kernely = np.array([[-1,",
"cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx) == 3: #Shape >>> vertices",
"width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2],",
"size[1], 3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)),",
"image = cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt =",
"self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size,",
"startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX",
"drawPrimitives(self, image, flag, points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True,",
"0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if auto: _,",
"Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i)",
"pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit, deci):",
"v = np.median(image.copy()) # apply automatic Canny edge detection using the computed median",
"= 1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /= 10 elif",
"/= 10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0] //",
"newH = dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci),",
"maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255),",
"if i==0 and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i,",
"if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image, text,",
"= newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr,",
"cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if",
"kar, width, height): if kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height))",
"if flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10,",
"# if flag==1: # rect pts = self.reorder(pts) if flag==1: #rect p1, p2,",
"bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 + 3, w+1:w + 2] =",
"sklearn.cluster import KMeans from skimage.morphology import * from skimage.util import * class OD_CV:",
"GK_size), GSigma) if cAuto: sigma = 0.33 v = np.median(image.copy()) # apply automatic",
"unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0] //",
"NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)]",
"p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0],",
"newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self):",
"np import warnings from sklearn.cluster import KMeans from skimage.morphology import * from skimage.util",
">>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and len(approx) == 4:",
"scale[1] - pt1[1] // scale[1]) ** 2) ** 0.5 # if flag==1: #",
"6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC x, y,",
"prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image",
"= np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp",
"width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag ==",
"elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0] // scale[0] -",
"= 0 arr, res = [], [] while True: cap = cv2.VideoCapture(index) if",
"imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask =",
"* 2 + 3] = (0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)):",
"= imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self, flag, pts, scale,",
"= cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx) == 3: #Shape >>>",
"thick) return finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2))",
"thick) elif flag == 4: x, y, w, h = points if width!=0:",
"np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image,",
"= cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes,",
"pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]:",
"image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max,",
"flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3,",
"self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img",
"len(approx) < 8: continue circularity = 4 * math.pi * (area / (peri*peri))",
"return palette def thinning(self, image, flag): image = img_as_float(image) if flag: #live streaming,",
"fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL",
"img_as_float(image) if flag: #live streaming, faster computation skeleton = skeletonize(image > 0) else:",
"GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H,",
"method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if auto: _, image",
"return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image",
"7: font = cv2.FONT_ITALIC x, y, w, h = coords if flag==1: cv2.putText(image,",
"= cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if flag==1:",
"endX return palette def thinning(self, image, flag): image = img_as_float(image) if flag: #live",
"over the percentage of each cluster and the color of # each cluster",
"return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3,",
"class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width, height):",
"c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick =",
"np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)]",
"[w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp",
"OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if",
"scale[0] - pt1[0] // scale[0]) ** 2 + (pt2[1] // scale[1] - pt1[1]",
"p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW =",
"not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index += 1 return arr,",
"import math import imutils import numpy as np import warnings from sklearn.cluster import",
"(width_Total, y-10-2), color, thick) elif flag == 4: x, y, w, h =",
"hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0",
"0, 0], [1, 1, 1]]) kernely = np.array([[-1, 0, 1], [-1, 0, 1],",
"0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w * 2 + 3] = (0,0,0)",
"points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints",
"pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image,",
"-1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image,",
"the color of # each cluster for percent, color in zip(hist, clt.cluster_centers_): #",
"len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if len(approx) <",
"h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height),",
"= points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1]",
"if not shape: continue area = cv2.contourArea(c) if area > minArea[i]: peri =",
"i==0 and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox))",
"thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in",
"(p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH",
"1, 1]]) kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])",
"image def drawPrimitives(self, image, flag, points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image,",
"[-1, 0, 1], [-1, 0, 1]]) kernely2 = np.array([[1, 0, -1], [1, 0,",
"return image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick): contours,",
"(width, height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask,",
"hist /= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 #",
"approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c)",
"image def reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1)",
"cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self, image, GK_size, GSigma, DK_size, D_i,",
"[1, 0, -1], [1, 0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img",
"auto, lower, max): if auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else:",
"cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img =",
"cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0,",
"max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)",
"max): if auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image",
"GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag):",
"pt1[0] // scale[0]) ** 2 + (pt2[1] // scale[1] - pt1[1] // scale[1])",
"-1], [1, 0, -1], [1, 0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2]",
"w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3]",
"size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if wid[0]>0:",
"height): if kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self,",
"imutils import numpy as np import warnings from sklearn.cluster import KMeans from skimage.morphology",
"cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg",
"isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if",
"1 if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2:",
"= cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx)",
"from skimage.util import * class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self,",
"= np.median(image.copy()) # apply automatic Canny edge detection using the computed median lower",
"dtype=\"uint8\") startX = 0 # loop over the percentage of each cluster and",
"thick) def drawText(self, flag, image, text, coords, fontstyle, color, thick, height=None): font =",
"points, size, pad=3): points = self.reorder(points) # if not size: w, h =",
"p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0], pts[1],",
"cv2.FONT_ITALIC x, y, w, h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font,",
"def warpImg(self, image, points, size, pad=3): points = self.reorder(points) # if not size:",
"// scale[1] - pt1[1] // scale[1]) ** 2) ** 0.5 # if flag==1:",
"DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray",
"points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h = size pts1 = np.float32(points) pts2",
"pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2)",
"= points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return",
"0, 1], [-1, 0, 1]]) kernely2 = np.array([[1, 0, -1], [1, 0, -1],",
"np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self, image,",
"(p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv return",
"2, 0:w * 2 + 3] = (0,0,0) return bg def Color_picker(self, color,",
"cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image def reorder(self, points): NewPoints =",
"(x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image, text, coords, fontstyle, color,",
"enumerate(shapes): if not shape: continue area = cv2.contourArea(c) if area > minArea[i]: peri",
"cluster and the color of # each cluster for percent, color in zip(hist,",
"to one hist = hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200, 3),",
"color of # each cluster for percent, color in zip(hist, clt.cluster_centers_): # plot",
"(GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(),",
"cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8)",
"elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font =",
"v)) upper = int(min(255, (1.0 + sigma) * v)) else: lower, upper =",
"= cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self, image, GK_size, GSigma, DK_size,",
"edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin,",
"cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary",
"= x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag == 4: x,",
"NewPoints def warpImg(self, image, points, size, pad=3): points = self.reorder(points) # if not",
"rbox)) elif i==2: if len(approx) < 8: continue circularity = 4 * math.pi",
"= cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image",
"= (0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1],",
"= np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size,",
"sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if",
"def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto,",
"image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg, minArea,",
"(sw,sh) def findDist(self, flag, pts, scale, unit, deci): unit_conv = 1 if unit[0]==0:",
"pt1[1] // scale[1]) ** 2) ** 0.5 # if flag==1: # rect pts",
"percentage of each cluster endX = startX + (percent * 200) cv2.rectangle(palette, (int(startX),",
"= image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i)",
"box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx) == 3: #Shape",
"the computed median lower = int(max(0, (1.0 - sigma) * v)) upper =",
"loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if kar: return",
"imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize)",
"cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin:",
"np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0],",
"with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) +",
"+ 3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h +",
"= 4 * math.pi * (area / (peri*peri)) if circular[0] < circularity <",
"bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 + 3,",
"iterations=E_i) return image, edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i,",
"edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick): contours, _ =",
"unit_conv /= 1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000",
"the relative percentage of each cluster endX = startX + (percent * 200)",
"#live streaming, faster computation skeleton = skeletonize(image > 0) else: # upload image",
"_ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours: for",
"image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H,",
"minArea, shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours =",
"#Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and len(approx) ==",
"hist = hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX",
"GSigma) if cAuto: sigma = 0.33 v = np.median(image.copy()) # apply automatic Canny",
"cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index += 1 return arr, res",
"in contours: for i, shape in enumerate(shapes): if not shape: continue area =",
"cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if flag==1: return",
"cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC x, y, w, h =",
"== 3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and",
"if flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2,",
"self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1,",
"= cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H)",
"= -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours,",
"= (255,255,255) bg[h+1:h + 2, 0:w * 2 + 3] = (0,0,0) return",
"y, w, h = points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w,",
"= (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv",
"= cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma = 0.33 v = np.median(image.copy())",
"newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr, res",
"= np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self,",
"= points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size, pad=3):",
"image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self, image, GK_size, GSigma,",
"v)) else: lower, upper = cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if",
"imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit,",
"lower, upper = cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if isThin: image",
"sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick = -1 for cont in finalCountours:",
"0:w * 2 + 3] = (0,0,0) return bg def Color_picker(self, color, size,",
"size, pad=3): points = self.reorder(points) # if not size: w, h = points[1][0][0]",
"= np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix,",
"[kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img =",
"return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None, 0.5,",
"warnings from sklearn.cluster import KMeans from skimage.morphology import * from skimage.util import *",
"w, h = points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height),",
"color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0:",
"// scale[0]) ** 2 + (pt2[1] // scale[1] - pt1[1] // scale[1]) **",
"hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that it sums",
"palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 # loop over the",
"return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if auto: _, image =",
"text, coords, fontstyle, color, thick, height=None): font = None if fontstyle == 0:",
"0, 1]]) kernely2 = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])",
"skeleton = skeletonize(image > 0) else: # upload image mode skeleton = skeletonize(image",
"cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and",
"each cluster for percent, color in zip(hist, clt.cluster_centers_): # plot the relative percentage",
"unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /=",
"dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\")",
"-1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image, coords): return",
"EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self, image, GK_size,",
"(int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255),",
"live_flag) image = prewitt_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size))",
"E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image =",
"i, rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox))",
"add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1)",
"True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release()",
"lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if flag==1: return cv2.cvtColor(image,",
"_ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that it sums to",
"cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray,",
"self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img",
"flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self,",
"-1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) kernely",
"circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx,",
"== 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC x,",
"kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img,",
"isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma)",
"GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres,",
"w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 + 3, w+1:w",
"0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0, 0],",
"img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if auto: _, image = cv2.threshold(image.copy(),",
"coords, fontstyle, color, thick, height=None): font = None if fontstyle == 0: font",
"EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(),",
"imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0, 0,",
"iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick):",
"3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle",
"prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy() if isDIL: Dial_K",
"cluster endX = startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40),",
"cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img =",
"1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle",
"int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1],",
"kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) kernelx2 =",
"True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx) rect =",
"- pt1[0] // scale[0]) ** 2 + (pt2[1] // scale[1] - pt1[1] //",
"* v)) upper = int(min(255, (1.0 + sigma) * v)) else: lower, upper",
"unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /=",
"if flag==1: # rect pts = self.reorder(pts) if flag==1: #rect p1, p2, p3",
"font, thick, color, 1) def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i,",
"color in zip(hist, clt.cluster_centers_): # plot the relative percentage of each cluster endX",
"None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font",
"h = points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color,",
"cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image",
"peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox =",
"continue circularity = 4 * math.pi * (area / (peri*peri)) if circular[0] <",
"matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad]",
"image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255)",
"finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0:",
"image): image = cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt",
"font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle ==",
"kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1,",
"np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3,",
"flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y, w,",
"rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx)",
"cAuto: sigma = 0.33 v = np.median(image.copy()) # apply automatic Canny edge detection",
"unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /=",
"image = np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01),",
"= points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick)",
"Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1)",
"def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings():",
"= np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that it sums to one",
"[0, 0, 0], [1, 1, 1]]) kernely = np.array([[-1, 0, 1], [-1, 0,",
"reverse=True) if thick==0: thick = -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1,",
"- pt1[1] // scale[1]) ** 2) ** 0.5 # if flag==1: # rect",
"color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self,",
"(peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif",
"color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2:",
"wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image,",
"-1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in",
"in zip(hist, clt.cluster_centers_): # plot the relative percentage of each cluster endX =",
"coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None, 0.5, 0.5) with",
"cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image, text, coords, fontstyle,",
"for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img",
"kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto,",
"deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr, res = [], []",
"2 + 3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h",
"minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) bbox",
"np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h))",
"kernely2 = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) kernels =",
"return ((pt2[0] // scale[0] - pt1[0] // scale[0]) ** 2 + (pt2[1] //",
"np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) imgWarp =",
"deviceList(self): index = 0 arr, res = [], [] while True: cap =",
"mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return",
"True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif",
"endX = startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(),",
"coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None,",
"deci) def deviceList(self): index = 0 arr, res = [], [] while True:",
"== 4: x, y, w, h = points if width!=0: w = width",
"< circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox,",
"== 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif",
"image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L,",
"finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add =",
"def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1,",
"0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_))",
"loop over the percentage of each cluster and the color of # each",
"height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts],",
"isThin: image = self.thinning(image) edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size))",
"cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def",
"0, 1], [-1, 0, 1], [-1, 0, 1]]) kernely2 = np.array([[1, 0, -1],",
"k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img =",
"(pt2[1] // scale[1] - pt1[1] // scale[1]) ** 2) ** 0.5 # if",
"cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours: for i, shape in",
"** 0.5 # if flag==1: # rect pts = self.reorder(pts) if flag==1: #rect",
"color.astype(\"uint8\").tolist(), -1) startX = endX return palette def thinning(self, image, flag): image =",
"cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i,",
"thick, color, 1) def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto,",
"lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 +",
"def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if kar:",
"+ 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such that",
"cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c in contours: for i, shape in enumerate(shapes):",
"font, thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1)",
"scale[1]) ** 2) ** 0.5 # if flag==1: # rect pts = self.reorder(pts)",
"len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram, such",
"(int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette def thinning(self, image, flag):",
"elif i==2: if len(approx) < 8: continue circularity = 4 * math.pi *",
"points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx",
"percentage of each cluster and the color of # each cluster for percent,",
"cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size),",
"sigma = 0.33 v = np.median(image.copy()) # apply automatic Canny edge detection using",
"1, 1], [0, 0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1],",
"255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def",
"if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img,",
"else: # upload image mode skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton)",
"x:x[1], reverse=True) if thick==0: thick = -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]],",
"image, points, size, pad=3): points = self.reorder(points) # if not size: w, h",
"w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w",
"cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font",
"clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _",
"width=None, height=None): if flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10,",
"GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres,",
"cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1,",
"prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L,",
"len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1",
"flag == 4: x, y, w, h = points if width!=0: w =",
"flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10),",
"= [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img",
"= self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image =",
"np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) kernely2 = np.array([[1, 0,",
"= points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size, pad=3): points = self.reorder(points)",
"np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self, image,",
"int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points,",
"sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy() if isDIL: Dial_K",
"and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif",
"= np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self,",
"import warnings from sklearn.cluster import KMeans from skimage.morphology import * from skimage.util import",
"return NewPoints def warpImg(self, image, points, size, pad=3): points = self.reorder(points) # if",
"[-1, 0, 1]]) kernely2 = np.array([[1, 0, -1], [1, 0, -1], [1, 0,",
"cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02",
"p1, p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else:",
"= np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)),",
"unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0]",
"warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist,",
"font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC x, y, w,",
"def deviceList(self): index = 0 arr, res = [], [] while True: cap",
"= image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] =",
"image, text, coords, fontstyle, color, thick, height=None): font = None if fontstyle ==",
"= cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY)",
"fontstyle == 7: font = cv2.FONT_ITALIC x, y, w, h = coords if",
"elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv",
"flag, pts, scale, unit, deci): unit_conv = 1 if unit[0]==0: unit_conv = 1",
"warpImg(self, image, points, size, pad=3): points = self.reorder(points) # if not size: w,",
"else: return cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8)",
"isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge = image.copy() if isDIL:",
"c, i, rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c, i,",
"numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize",
"if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3:",
"= points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx =",
"flag, points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True, color, thick)",
"wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points, color, thick, width=None, height=None):",
"in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(),",
"imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp,",
"elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font =",
"E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1)",
"c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours,",
"d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def",
"-1) startX = endX return palette def thinning(self, image, flag): image = img_as_float(image)",
"cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font",
"image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1)",
"-1, -1], [0, 0, 0], [1, 1, 1]]) kernely = np.array([[-1, 0, 1],",
"np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image,",
"mode skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto,",
"thick = -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return",
"(255,255,255) bg[h+1:h + 2, 0:w * 2 + 3] = (0,0,0) return bg",
"def thinning(self, image, flag): image = img_as_float(image) if flag: #live streaming, faster computation",
"unit, deci): unit_conv = 1 if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv",
"unit_conv = 1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1: unit_conv /= 10",
"newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0",
"palette def thinning(self, image, flag): image = img_as_float(image) if flag: #live streaming, faster",
"- sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) else:",
"= cv2.resize(image, (0, 0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5,",
"def canny(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL,",
"scale[0]) ** 2 + (pt2[1] // scale[1] - pt1[1] // scale[1]) ** 2)",
"unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0]",
"* 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return",
"np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 # loop over the percentage of",
"2 + (pt2[1] // scale[1] - pt1[1] // scale[1]) ** 2) ** 0.5",
"numpy as np import warnings from sklearn.cluster import KMeans from skimage.morphology import *",
"startX = endX return palette def thinning(self, image, flag): image = img_as_float(image) if",
"= np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) kernels = [kernelx,",
"cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image def reorder(self,",
"flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3",
"+ 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w *",
"# each cluster for percent, color in zip(hist, clt.cluster_centers_): # plot the relative",
"Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma)",
"edge detection using the computed median lower = int(max(0, (1.0 - sigma) *",
"0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto,",
"= size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix =",
"= hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX =",
"each cluster endX = startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX),",
"self.reorder(pts) if flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1,",
"color, thick) elif flag == 4: x, y, w, h = points if",
"points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] =",
"import * class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar,",
"if thick==0: thick = -1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color,",
"flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image, GK_size, GSigma,",
"isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx",
"3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2,",
"x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag == 4: x, y,",
"not shape: continue area = cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c,",
"reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] =",
"pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW",
"sw,sh = w/size[0], h/size[1] # w,h = size pts1 = np.float32(points) pts2 =",
"font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle ==",
"-1], [1, 0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray)",
"isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag)",
"cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if kar: return imutils.resize(image, width=width) else:",
"i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda",
"= cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7:",
"axis=1) NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points,",
"sums to one hist = hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40, 200,",
"= cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5:",
"self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1],",
"cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def",
"findDist(self, flag, pts, scale, unit, deci): unit_conv = 1 if unit[0]==0: unit_conv =",
"upper = int(min(255, (1.0 + sigma) * v)) else: lower, upper = cThres_L,",
"= [], [] while True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break else:",
"elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y,",
"E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(),",
"finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick = -1 for cont",
"True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box)",
"the histogram, such that it sums to one hist = hist.astype(\"float\") hist /=",
"Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def",
"= cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize)",
"_, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag):",
"if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW = newW*unit_conv",
"= 10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /= 1 elif",
"skimage.morphology import * from skimage.util import * class OD_CV: def loadImage(self, filepath): return",
"NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2]",
"unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv =",
"* 2 + 3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255)",
"zip(hist, clt.cluster_centers_): # plot the relative percentage of each cluster endX = startX",
"x, y, w, h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick,",
"width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag,",
"rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1],",
"mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image =",
"_, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower,",
"= image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] =",
"and len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if len(approx)",
"bg[h+1:h + 2, 0:w * 2 + 3] = (0,0,0) return bg def",
"isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur =",
"color, thick, height=None): font = None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX",
"if auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image =",
"font = None if fontstyle == 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle ==",
"elif i==3: finalCountours.append((approx, bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True)",
"points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h = size pts1",
"points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2),",
"bbox, c, i, rbox)) elif i==2: if len(approx) < 8: continue circularity =",
"circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c,",
"h/size[1] # w,h = size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h],",
"width, height): if kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def",
"getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL,",
"height=None): if flag==1: cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10),",
"cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font,",
"color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3:",
"= img_as_float(image) if flag: #live streaming, faster computation skeleton = skeletonize(image > 0)",
"(int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag,",
"cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index += 1",
"if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image):",
"elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv",
"= self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F,",
"isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto:",
"cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font",
"hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 # loop over",
"+ (pt2[1] // scale[1] - pt1[1] // scale[1]) ** 2) ** 0.5 #",
"w,h = size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix",
"cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image) edge = image.copy() if isDIL:",
"cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma = 0.33 v = np.median(image.copy()) #",
"width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image, text, coords,",
"image, kar, width, height): if kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width,",
"* class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image, kar, width,",
"from skimage.morphology import * from skimage.util import * class OD_CV: def loadImage(self, filepath):",
"image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def sobel(self, image, GK_size, GSigma,",
"shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = []",
"= self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy() if isDIL: Dial_K =",
"/= hist.sum() palette = np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 # loop",
"thinning(self, image, flag): image = img_as_float(image) if flag: #live streaming, faster computation skeleton",
"color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for c",
"((pt2[0] // scale[0] - pt1[0] // scale[0]) ** 2 + (pt2[1] // scale[1]",
"image = prewitt_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image",
"= skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max):",
"c, i, rbox)) elif i==2: if len(approx) < 8: continue circularity = 4",
"# w,h = size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]])",
"= color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if",
"index = 0 arr, res = [], [] while True: cap = cv2.VideoCapture(index)",
"size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] #",
"8: continue circularity = 4 * math.pi * (area / (peri*peri)) if circular[0]",
"Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size,",
"kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(),",
"p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW = newW*unit_conv newH",
"computation skeleton = skeletonize(image > 0) else: # upload image mode skeleton =",
"np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) kernely = np.array([[-1, 0,",
"(x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag == 4: x, y, w, h",
"[1, 1, 1]]) kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0,",
"rbox = np.int0(box) if i==0 and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx,",
"font = cv2.FONT_ITALIC x, y, w, h = coords if flag==1: cv2.putText(image, text,",
"return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w =",
"bins=numLabels) # normalize the histogram, such that it sums to one hist =",
"self.reorder(points) # if not size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh",
"boundary return imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit, deci): unit_conv =",
"newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index =",
"0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette def thinning(self, image,",
"= int(min(255, (1.0 + sigma) * v)) else: lower, upper = cThres_L, cThres_H",
"= dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3)",
"pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return",
"image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3],",
"i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if",
"-1 for cont in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image",
"= cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if isThin: image = self.thinning(image)",
"lower, max): if auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _,",
"font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle ==",
"(1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v))",
"(int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette def thinning(self,",
"= np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self,",
"/ (peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c, i, rbox))",
"finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image def reorder(self, points): NewPoints",
"= cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c,",
"cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return",
"2) ** 0.5 # if flag==1: # rect pts = self.reorder(pts) if flag==1:",
"= np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1]",
"GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])",
"pts, scale, unit, deci): unit_conv = 1 if unit[0]==0: unit_conv = 1 elif",
"DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image",
"cap = cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) cap.release() index",
"skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower,",
"\"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr, res = [], [] while",
"image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image =",
"if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag",
"Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres:",
"if kar: return imutils.resize(image, width=width) else: return cv2.resize(image, (width, height)) def maskIMG(self, image,",
"return finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add",
"fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX",
"(GK_size, GK_size), GSigma) if cAuto: sigma = 0.33 v = np.median(image.copy()) # apply",
"newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW = newW*unit_conv newH =",
"sobel_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image,",
"vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx,",
"points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y, w, h = points",
"else: _, image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image,",
"points = self.reorder(points) # if not size: w, h = points[1][0][0] - points[0][0][0],",
"2] = (0,0,0) bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w * 2",
"= np.int0(box) if i==0 and len(approx) == 3: #Shape >>> vertices finalCountours.append((approx, bbox,",
"color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if",
"scale, unit, deci): unit_conv = 1 if unit[0]==0: unit_conv = 1 elif unit[0]==1:",
"= cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin:",
"upload image mode skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self,",
"fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN",
"if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img,",
"if isThin: image = self.thinning(image) edge = image.copy() if isDIL: Dial_K = np.ones((DK_size,",
"5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle == 6: font = cv2.FONT_HERSHEY_TRIPLEX elif fontstyle",
"k in kernels: prewitt_img = cv2.bitwise_or(prewitt_img, cv2.filter2D(imgBlur.copy(), -1, k)) if isThres: prewitt_img =",
"== 0: font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif",
"flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5),",
"skimage.util import * class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def resizeImage(self, image,",
"(255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image, coords):",
"in enumerate(shapes): if not shape: continue area = cv2.contourArea(c) if area > minArea[i]:",
"else: newH = dist(p1, p3) newW = newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW,",
"h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif",
"* from skimage.util import * class OD_CV: def loadImage(self, filepath): return cv2.imread(filepath) def",
"3: #Shape >>> vertices finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and len(approx)",
"points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h = size pts1 = np.float32(points)",
"mask=mask) return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image):",
"normalize the histogram, such that it sums to one hist = hist.astype(\"float\") hist",
"4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if len(approx) < 8: continue",
"0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3]",
"return image def drawPrimitives(self, image, flag, points, color, thick, width=None, height=None): if flag==1:",
"font = cv2.FONT_HERSHEY_COMPLEX elif fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle ==",
"elif flag==3: x, y, w, h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10:",
"= int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma)",
"* (area / (peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox, c,",
"import imutils import numpy as np import warnings from sklearn.cluster import KMeans from",
"KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_,",
"cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette def",
"isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge",
"NewPoints[1] = points[np.argmin(d_dx)] NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size,",
"each cluster and the color of # each cluster for percent, color in",
"apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0",
"flag: #live streaming, faster computation skeleton = skeletonize(image > 0) else: # upload",
"3] = (0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0],",
"image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3]",
"isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K",
"1]]) kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) kernely2",
"y, w, h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color,",
"w, h = coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1)",
"p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW",
"KMeans from skimage.morphology import * from skimage.util import * class OD_CV: def loadImage(self,",
"image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] =",
"bg[h:h+3, 0:w*2+3] = (255,255,255) bg[h+1:h + 2, 0:w * 2 + 3] =",
"[0, 0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0,",
"finalCountours.append((approx, bbox, c, i, rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox,",
"int(min(255, (1.0 + sigma) * v)) else: lower, upper = cThres_L, cThres_H image",
"points.sum(1) NewPoints[0] = points[np.argmin(add)] NewPoints[2] = points[np.argmax(add)] d_dx = np.diff(points, axis=1) NewPoints[1] =",
"pt2): return ((pt2[0] // scale[0] - pt1[0] // scale[0]) ** 2 + (pt2[1]",
"if not size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0],",
"image = sobel_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image",
"image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA)",
"= self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma =",
"lower, upper) if isThin: image = self.thinning(image) edge = image.copy() if isDIL: Dial_K",
"c in contours: for i, shape in enumerate(shapes): if not shape: continue area",
"# if not size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh =",
"bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3,",
"def drawText(self, flag, image, text, coords, fontstyle, color, thick, height=None): font = None",
"np.median(image.copy()) # apply automatic Canny edge detection using the computed median lower =",
"image = cv2.threshold(image.copy(), lower, max, cv2.THRESH_BINARY) return image def color_CVT(self, image, flag): if",
"imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(),",
"\"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index = 0 arr, res = [],",
"matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove boundary return imgWarp, (sw,sh) def findDist(self,",
"= self.reorder(pts) if flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else:",
"= startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1)",
"cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)),",
"image, flag, points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True, color,",
"else: lower, upper = cThres_L, cThres_H image = cv2.Canny(image, lower, upper) if isThin:",
"i, rbox)) elif i==2: if len(approx) < 8: continue circularity = 4 *",
"== 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif",
"i, shape in enumerate(shapes): if not shape: continue area = cv2.contourArea(c) if area",
"Ero_K, iterations=E_i) return image, edge def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size,",
"coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image,",
"pts): mask = np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image",
"cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick) elif flag == 4: x, y, w,",
"EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image",
"sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto,",
"points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points, True, color, thick) elif",
"1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image,",
"[], [] while True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index))",
"fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX",
"cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img",
"isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X",
"math.pi * (area / (peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx, bbox,",
"= coords if flag==1: cv2.putText(image, text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2:",
"as np import warnings from sklearn.cluster import KMeans from skimage.morphology import * from",
"D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray =",
"-1, color, thick) return finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points) points",
"histogram, such that it sums to one hist = hist.astype(\"float\") hist /= hist.sum()",
"text, (x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick,",
"(int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points, color,",
"3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] =",
"= (255,255,255) bg[0:h * 2 + 3, w+1:w + 2] = (0,0,0) bg[h:h+3,",
"np.zeros((size[0], size[1], 3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99),",
"self.thinning(image) edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image,",
"== 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif",
"#remove boundary return imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit, deci): unit_conv",
"kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img = np.zeros_like(imgGray) for k in kernels:",
"elif fontstyle == 4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font =",
"w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w]",
"return cv2.imread(filepath) def resizeImage(self, image, kar, width, height): if kar: return imutils.resize(image, width=width)",
"computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255,",
"skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image, auto, lower, max): if",
"(x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image, text, coords, fontstyle, color, thick,",
"1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0,",
"image, image_edg, minArea, shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)",
"shape: continue area = cv2.contourArea(c) if area > minArea[i]: peri = cv2.arcLength(c, True)",
"for percent, color in zip(hist, clt.cluster_centers_): # plot the relative percentage of each",
"Ero_K, iterations=E_i) return image, edge def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color,",
"not size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1]",
"rect pts = self.reorder(pts) if flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0],",
"(int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9),",
"size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0], [w,h], [0,h]]) matrix = cv2.getPerspectiveTransform(pts1,",
"bbox, c, i, rbox)) elif i==1 and len(approx) == 4: finalCountours.append((approx, bbox, c,",
"= 0 # loop over the percentage of each cluster and the color",
"pts = self.reorder(pts) if flag==1: #rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0]",
"Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1,",
"#rect p1, p2, p3 = pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 =",
"using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper",
"else: newW = dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH =",
"circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i, rbox))",
"points): NewPoints = np.zeros_like(points) points = points.reshape((4,2)) add = points.sum(1) NewPoints[0] = points[np.argmin(add)]",
"-1], [0, 0, 0], [1, 1, 1]]) kernely = np.array([[-1, 0, 1], [-1,",
"3), np.uint8) image[:] = color if wid[0]>0: cv2.rectangle(image, (int(size[0]*.01), int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0),",
"y-10-2), color, thick) elif flag == 4: x, y, w, h = points",
"cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image, Ero_K,",
"color, thick) elif flag==3: x, y, w, h = points width_Total = x+int(w*0.05)+width",
"1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L,",
"< circular[1]: finalCountours.append((approx, bbox, c, i, rbox)) elif i==3: finalCountours.append((approx, bbox, c, i,",
"fontstyle == 1: font = cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX",
"thick) elif flag==3: x, y, w, h = points width_Total = x+int(w*0.05)+width if",
"upper) if isThin: image = self.thinning(image) edge = image.copy() if isDIL: Dial_K =",
"= points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total,",
"GSigma) kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) kernelx2",
"image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None):",
"pts[0][0], pts[1][0], pts[3][0] else: p1, p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]:",
"x, y, w, h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total =",
"# loop over the percentage of each cluster and the color of #",
"peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox =",
"cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def",
"0 # loop over the percentage of each cluster and the color of",
"cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font",
"skeletonize(image > 0) else: # upload image mode skeleton = skeletonize(image > 0,",
"live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X =",
"p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW =",
"0.33 v = np.median(image.copy()) # apply automatic Canny edge detection using the computed",
"elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font =",
"NewPoints[3] = points[np.argmax(d_dx)] return NewPoints def warpImg(self, image, points, size, pad=3): points =",
"/= 1000 def dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0] // scale[0])",
"auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) else: _, image = cv2.threshold(image.copy(),",
"= endX return palette def thinning(self, image, flag): image = img_as_float(image) if flag:",
"image, auto, lower, max): if auto: _, image = cv2.threshold(image.copy(), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)",
"np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size))",
"[-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1,",
"int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) *",
"if flag: #live streaming, faster computation skeleton = skeletonize(image > 0) else: #",
"edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K,",
"0.02 * peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect)",
"- points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h = size pts1 =",
"= np.zeros((40, 200, 3), dtype=\"uint8\") startX = 0 # loop over the percentage",
"warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)",
"+ 3] = (0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)): image =",
"0], [1, 1, 1]]) kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1,",
"w, h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image,",
"live_flag) image = sobel_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size))",
"0) else: # upload image mode skeleton = skeletonize(image > 0, method='lee') return",
"1], [-1, 0, 1], [-1, 0, 1]]) kernely2 = np.array([[1, 0, -1], [1,",
"of # each cluster for percent, color in zip(hist, clt.cluster_centers_): # plot the",
"x, y, w, h = points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h),",
"dist(pt1, pt2): return ((pt2[0] // scale[0] - pt1[0] // scale[0]) ** 2 +",
"DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(),",
"cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y =",
"= [] for c in contours: for i, shape in enumerate(shapes): if not",
"image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image, (0, 0), None, 0.5, 0.5)",
"cv2.resize(image, (width, height)) def maskIMG(self, image, pts): mask = np.zeros(image.shape[:2], np.uint8) mask =",
"(points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y, w, h =",
"i==2: if len(approx) < 8: continue circularity = 4 * math.pi * (area",
"key=lambda x:x[1], reverse=True) if thick==0: thick = -1 for cont in finalCountours: cv2.drawContours(image,",
"= np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(),",
"40), color.astype(\"uint8\").tolist(), -1) startX = endX return palette def thinning(self, image, flag): image",
"return image, edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL,",
"circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) finalCountours = [] for",
"= cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]]",
"(points[0]+points[2]+10, points[1]+points[3]+10), color, thick) elif flag==3: x, y, w, h = points width_Total",
"image mode skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def thresholding(self, image,",
"Thres_L, Thres_H) if isThin: prewitt_img = self.thinning(prewitt_img, live_flag) image = prewitt_img edge =",
"unit_conv = 1 if unit[0]==0: unit_conv = 1 elif unit[0]==1: unit_conv = 10",
"// scale[0] - pt1[0] // scale[0]) ** 2 + (pt2[1] // scale[1] -",
"[cont[2]], -1, color, thick) return finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points)",
"and the color of # each cluster for percent, color in zip(hist, clt.cluster_centers_):",
"cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image, GK_size, GSigma, DK_size,",
"elif flag == 4: x, y, w, h = points if width!=0: w",
"= np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) kernelx2 = np.array([[-1,",
"bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] =",
"def resizeImage(self, image, kar, width, height): if kar: return imutils.resize(image, width=width) else: return",
"flag): image = img_as_float(image) if flag: #live streaming, faster computation skeleton = skeletonize(image",
"bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if",
"10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /= 1 elif unit[1]==1:",
"Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge",
"image, flag): if flag==1: return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def",
"[] for c in contours: for i, shape in enumerate(shapes): if not shape:",
"sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image",
"image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 +",
"prewitt_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image,",
"finalCountours = [] for c in contours: for i, shape in enumerate(shapes): if",
"10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2): return ((pt2[0] // scale[0]",
"cv2.polylines(image, points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color,",
"= cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image = cv2.erode(image,",
"> minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True)",
"faster computation skeleton = skeletonize(image > 0) else: # upload image mode skeleton",
"= x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10 cv2.rectangle(image, (x+int(w*0.05),y-10-height), (width_Total, y-10-2), color, thick)",
"cv2 import math import imutils import numpy as np import warnings from sklearn.cluster",
"bbox, c, i, rbox)) finalCountours = sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick",
"text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image, GK_size, GSigma, DK_size, D_i,",
"Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size),",
"it sums to one hist = hist.astype(\"float\") hist /= hist.sum() palette = np.zeros((40,",
"image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if",
"edge def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL, isERO,",
"dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1] else: newH = dist(p1, p3) newW",
"# apply automatic Canny edge detection using the computed median lower = int(max(0,",
"200, 3), dtype=\"uint8\") startX = 0 # loop over the percentage of each",
"[] while True: cap = cv2.VideoCapture(index) if not cap.read()[0]: break else: arr.append(str(index)) res.append((cap.get(cv2.CAP_PROP_FRAME_WIDTH),",
"color, thick) def drawText(self, flag, image, text, coords, fontstyle, color, thick, height=None): font",
"= skeletonize(image > 0) else: # upload image mode skeleton = skeletonize(image >",
"if isDIL: Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO:",
"1], [-1, 0, 1]]) kernely2 = np.array([[1, 0, -1], [1, 0, -1], [1,",
"cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points, color, thick, width=None, height=None): if",
"image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h * 2 + 3, w+1:w + 2]",
"3)) numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) #",
"bg def Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:]",
"def drawPrimitives(self, image, flag, points, color, thick, width=None, height=None): if flag==1: cv2.polylines(image, points,",
"= sobel_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image =",
"in finalCountours: cv2.drawContours(image, [cont[2]], -1, color, thick) return finalCountours, image def reorder(self, points):",
"pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2)",
"= cv2.FONT_HERSHEY_TRIPLEX elif fontstyle == 7: font = cv2.FONT_ITALIC x, y, w, h",
"1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1, 1], [0,",
"resizeImage(self, image, kar, width, height): if kar: return imutils.resize(image, width=width) else: return cv2.resize(image,",
"= sorted(finalCountours, key=lambda x:x[1], reverse=True) if thick==0: thick = -1 for cont in",
"isThres: sobel_img = self.thresholding(sobel_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag)",
"newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]: newH = (p3[1]-p1[1])//scale[1]",
"0:w] = image[2] bg[h+3:h*2+3, w+3:w*2+3] = image[3] bg[0:h*2+3, w:w+3] = (255,255,255) bg[0:h *",
"Ero_K, iterations=E_i) return image, edge def prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size,",
"imgWarp, (sw,sh) def findDist(self, flag, pts, scale, unit, deci): unit_conv = 1 if",
"cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox = np.int0(box) if i==0 and len(approx) == 3:",
"finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if len(approx) < 8: continue circularity",
"(x+int(w*0.07),y-19), font, thick, color, 1) elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color,",
"w/size[0], h/size[1] # w,h = size pts1 = np.float32(points) pts2 = np.float32([[0,0], [w,0],",
"= newW*unit_conv newH = newH*unit_conv return \"{:.{}f}\".format(newW, deci), \"{:.{}f}\".format(newH, deci) def deviceList(self): index",
"prewitt(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, isDIL, isERO, isThin, Thres_auto, Thres_L,",
"unit_conv = 10 elif unit[0]==2: unit_conv = 1000 if unit[1]==0: unit_conv /= 1",
"cluster for percent, color in zip(hist, clt.cluster_centers_): # plot the relative percentage of",
"isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge = image.copy() if isDIL:",
"np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) kernels = [kernelx, kernelx2,",
"def findDist(self, flag, pts, scale, unit, deci): unit_conv = 1 if unit[0]==0: unit_conv",
"GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F,",
"image, flag): image = img_as_float(image) if flag: #live streaming, faster computation skeleton =",
"(255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image, flag, points, color, thick, width=None,",
"np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the histogram,",
"median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0",
"flag, image, text, coords, fontstyle, color, thick, height=None): font = None if fontstyle",
"= self.thinning(image) edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image =",
"ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if",
"kernelx2 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) kernely =",
"relative percentage of each cluster endX = startX + (percent * 200) cv2.rectangle(palette,",
"iterations=E_i) return image, edge def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i,",
"1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma = 0.33 v",
"# upload image mode skeleton = skeletonize(image > 0, method='lee') return img_as_ubyte(skeleton) def",
"fontstyle, color, thick, height=None): font = None if fontstyle == 0: font =",
"4: font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle",
"return image, edge def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize,",
"0, -1], [1, 0, -1]]) kernels = [kernelx, kernelx2, kernely, kernely2] prewitt_img =",
"= w/size[0], h/size[1] # w,h = size pts1 = np.float32(points) pts2 = np.float32([[0,0],",
"= 1 elif unit[0]==1: unit_conv = 10 elif unit[0]==2: unit_conv = 1000 if",
"cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def drawPrimitives(self, image,",
"= cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3: font = cv2.FONT_HERSHEY_PLAIN elif fontstyle == 4:",
"elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2] bg =",
"elif flag==2: cv2.putText(image, text, (x-10,y+10+h+height-5), font, thick, color, 1) def canny(self, image, GK_size,",
"if len(approx) < 8: continue circularity = 4 * math.pi * (area /",
"points, True, color, thick) elif flag==2: cv2.rectangle(image, (points[0]-10, points[1]-10), (points[0]+points[2]+10, points[1]+points[3]+10), color, thick)",
"color, thick) return finalCountours, image def reorder(self, points): NewPoints = np.zeros_like(points) points =",
"EK_size, E_i, Ksize, isDIL, isERO, isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray =",
"/= 1 elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000 def",
"Dial_K = np.ones((DK_size, DK_size)) image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K =",
"0], [-1, -1, -1]]) kernelx2 = np.array([[-1, -1, -1], [0, 0, 0], [1,",
"0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y))",
"2 + 3] = (0,0,0) return bg def Color_picker(self, color, size, wid=(10,20)): image",
"0), None, 0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels",
"= cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) Sobel_X = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y",
"of each cluster and the color of # each cluster for percent, color",
"self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) if cAuto: sigma = 0.33",
"image, edge def sobel(self, image, GK_size, GSigma, DK_size, D_i, EK_size, E_i, Ksize, isDIL,",
"Thres_L, Thres_H) if isThin: sobel_img = self.thinning(sobel_img, live_flag) image = sobel_img edge =",
"0.5, 0.5) with warnings.catch_warnings(): warnings.simplefilter(\"ignore\") clt = KMeans(n_clusters=5, random_state=0).fit(image.reshape(-1, 3)) numLabels = np.arange(0,",
"if area > minArea[i]: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 *",
"* peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) rbox",
"isThin, Thres_auto, Thres_L, Thres_H, isThres, live_flag): imgGray = self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray,",
"pad=3): points = self.reorder(points) # if not size: w, h = points[1][0][0] -",
"elif unit[1]==1: unit_conv /= 10 elif unit[1]==2: unit_conv /= 1000 def dist(pt1, pt2):",
"0 arr, res = [], [] while True: cap = cv2.VideoCapture(index) if not",
"= cv2.FONT_HERSHEY_COMPLEX_SMALL elif fontstyle == 2: font = cv2.FONT_HERSHEY_DUPLEX elif fontstyle == 3:",
"of each cluster endX = startX + (percent * 200) cv2.rectangle(palette, (int(startX), 0),",
"def getTarget_Contour(self, image, image_edg, minArea, shapes, circular, color, thick): contours, _ = cv2.findContours(image_edg.copy(),",
"* math.pi * (area / (peri*peri)) if circular[0] < circularity < circular[1]: finalCountours.append((approx,",
"if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)), (255,255,255), wid[1], cv2.LINE_AA) return image def",
"flag==3: x, y, w, h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total",
"image = img_as_float(image) if flag: #live streaming, faster computation skeleton = skeletonize(image >",
"def cropIMG(self, image, coords): return image[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]] def dmntCOLOR(self, image): image = cv2.resize(image,",
"# normalize the histogram, such that it sums to one hist = hist.astype(\"float\")",
"image = cv2.dilate(image, Dial_K, iterations=D_i) if isERO: Ero_K = np.ones((EK_size, EK_size)) image =",
"int(size[1]*.01)), (int(size[0]*.99), int(size[1]*.99)), (0,0,0), wid[0], cv2.LINE_AA) if wid[1]>0: cv2.rectangle(image, (int(size[0]*.1), int(size[1]*.1)), (int(size[0]*.9), int(size[1]*.9)),",
"+ sigma) * v)) else: lower, upper = cThres_L, cThres_H image = cv2.Canny(image,",
"np.zeros(image.shape[:2], np.uint8) mask = cv2.drawContours(mask, [pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(),",
"= prewitt_img edge = image.copy() if isDIL: Dial_K = np.ones((DK_size, DK_size)) image =",
"> 0) else: # upload image mode skeleton = skeletonize(image > 0, method='lee')",
"= cv2.getPerspectiveTransform(pts1, pts2) imgWarp = cv2.warpPerspective(image, matrix, (w,h)) imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad:imgWarp.shape[1]-pad] #remove",
"def compareIMG(self, image): h,w = image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h,",
"font = cv2.FONT_HERSHEY_SCRIPT_COMPLEX elif fontstyle == 5: font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX elif fontstyle ==",
"bg[0:h * 2 + 3, w+1:w + 2] = (0,0,0) bg[h:h+3, 0:w*2+3] =",
"if p1[1]==p2[1]: newW = (p2[0]-p1[0])//scale[0] else: newW = dist(p1, p2) if p1[0]==p3[0]: newH",
"w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def drawText(self, flag, image,",
"EK_size)) image = cv2.erode(image, Ero_K, iterations=E_i) return image, edge def prewitt(self, image, GK_size,",
"= image[0].shape[:2] bg = np.zeros((h*2+3, w*2+3, 3), np.uint8) bg[0:h, 0:w] = image[0] bg[0:h,",
"points if width!=0: w = width cv2.rectangle(image, (x-10,y+10+h), (x+10+w, y+10+h+height), color, thick) def",
"y, w, h = points width_Total = x+int(w*0.05)+width if width_Total>x+w+10: width_Total = x+w+10",
"cv2.CV_64F, 1, 0, ksize=Ksize) Sobel_Y = cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img =",
"== 7: font = cv2.FONT_ITALIC x, y, w, h = coords if flag==1:",
"cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) elif flag==2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) def compareIMG(self, image): h,w = image[0].shape[:2]",
"(percent * 200) cv2.rectangle(palette, (int(startX), 0), (int(endX), 40), color.astype(\"uint8\").tolist(), -1) startX = endX",
"= np.arange(0, len(np.unique(clt.labels_)) + 1) hist, _ = np.histogram(clt.labels_, bins=numLabels) # normalize the",
"bg[0:h, 0:w] = image[0] bg[0:h, w+3:w*2+3] = image[1] bg[h+3:h*2+3, 0:w] = image[2] bg[h+3:h*2+3,",
"= cv2.approxPolyDP(c, 0.02 * peri, True) bbox = cv2.boundingRect(approx) rect = cv2.minAreaRect(c) box",
"pts[3][0] else: p1, p2, p3 = pts[0], pts[1], pts[3] if p1[1]==p2[1]: newW =",
"[pts], -1, (255,255,255), -1) image = cv2.bitwise_and(image.copy(), image.copy(), mask=mask) return image def cropIMG(self,",
"= self.color_CVT(image.copy(), 1) imgBlur = cv2.GaussianBlur(imgGray, (GK_size, GK_size), GSigma) kernelx = np.array([[1, 1,",
"GK_size, GSigma, DK_size, D_i, EK_size, E_i, cAuto, cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray",
"= self.reorder(points) # if not size: w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1]",
"= cv2.Sobel(imgBlur.copy(), cv2.CV_64F, 0, 1, ksize=Ksize) sobel_img = cv2.bitwise_or(cv2.convertScaleAbs(Sobel_X), cv2.convertScaleAbs(Sobel_Y)) if isThres: sobel_img",
"== 4: finalCountours.append((approx, bbox, c, i, rbox)) elif i==2: if len(approx) < 8:",
"-1, k)) if isThres: prewitt_img = self.thresholding(prewitt_img.copy(), Thres_auto, Thres_L, Thres_H) if isThin: prewitt_img",
"Color_picker(self, color, size, wid=(10,20)): image = np.zeros((size[0], size[1], 3), np.uint8) image[:] = color",
"w, h = points[1][0][0] - points[0][0][0], points[3][0][1]-points[0][0][1] sw,sh = w/size[0], h/size[1] # w,h",
"cThres_L, cThres_H, isDIL, isERO, isThin=None): imgGray = self.color_CVT(image.copy(), 1) image = cv2.GaussianBlur(imgGray, (GK_size,"
] |
[
"from hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue --\\n') #",
"self.port = port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)",
"self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self,",
"%s\" % result) return result # code leftover from hacking # def getText(self,",
"to launch Vim instance that use clientserver mode to communicate with Vim instance",
"return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if",
"False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb):",
"closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message,",
"vimpdb import config from vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path =",
"return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read()",
"self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status",
"self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN)",
"%s\" % message) return message # code leftover from hacking # def eat_stdin(self):",
"server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts def _remote_expr(self, expr):",
"self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code:",
"not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command",
"filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility:",
"expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result # code leftover",
"in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename,",
"= self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result # code leftover from hacking",
"class Communicator(object): def __init__(self, script, server_name): self.script = script self.server_name = server_name def",
"errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch Vim instance that use clientserver",
"self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise",
"= 512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive = True self.port =",
"BUFLEN = 512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive = True self.port",
"self.socket_inactive = False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True def",
"subprocess to launch Vim instance that use clientserver mode to communicate with Vim",
"def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim",
"= config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name):",
"command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>'",
"self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\"",
"errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return output.strip() def _send(self, command): #",
"self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename",
"% prompt) # return command class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket",
"# def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue --\\n') # sys.stdout.flush() #",
"def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path),",
"to communicate with Vim instance used for debugging. \"\"\" def __init__(self, communicator): self.communicator",
"repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def",
"= feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not feedback:",
"return command class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def __init__(self, port):",
"_send(self, command): # add ':<BS>' to hide last keys sent in VIM command-line",
"parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable()",
"communicate with Vim instance used for debugging. \"\"\" def __init__(self, communicator): self.communicator =",
"self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message # code leftover from hacking #",
"them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno))",
"use subprocess to launch Vim instance that use clientserver mode to communicate with",
"# So turn backslash to slash; Vim knows how to translate them back.",
"= server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts def _remote_expr(self,",
"# source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source",
"if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\")",
"socket.socket def __init__(self, port): self.socket_inactive = True self.port = port def bindSocket(self): if",
"stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output =",
"= port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET,",
"self.socket_inactive = True self.port = port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory(",
"sent in VIM command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\",",
"line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename):",
"from hacking # def getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' %",
"bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('',",
"filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path",
"self.port)) self.socket_inactive = False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True",
"result) return result # code leftover from hacking # def getText(self, prompt): #",
"p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return output.strip()",
"filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self,",
"So turn backslash to slash; Vim knows how to translate them back. filename",
"def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket()",
"ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive = True",
"self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows command-line does",
"hacking # def getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt)",
"pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message #",
"proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename",
"self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback): if not feedback: return feedback_list",
"subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch Vim",
"os import socket import subprocess from vimpdb import config from vimpdb import errors",
"script, server_name): self.script = script self.server_name = server_name def prepare_subprocess(self, *args): parts =",
"def showFeedback(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>'",
"Vim instance that use clientserver mode to communicate with Vim instance used for",
"parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait()",
"instance that use clientserver mode to communicate with Vim instance used for debugging.",
"expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return",
"import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), )",
"def __init__(self, communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" %",
"hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue --\\n') # sys.stdout.flush()",
"= os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in",
"import socket import subprocess from vimpdb import config from vimpdb import errors def",
"expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code =",
"self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command:",
"__init__(self, port): self.socket_inactive = True self.port = port def bindSocket(self): if self.socket_inactive: self.socket",
"command-line does not play well with backslash in filename. # So turn backslash",
"\"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use",
"parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts,",
"\"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path))",
"Vim instance used for debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator def",
"os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows command-line",
"if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return output.strip() def",
"= feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line))",
"PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback):",
") class Communicator(object): def __init__(self, script, server_name): self.script = script self.server_name = server_name",
"os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name): self.script = script self.server_name =",
"def _send(self, command): # add ':<BS>' to hide last keys sent in VIM",
"command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts)",
"port): self.socket_inactive = True self.port = port def bindSocket(self): if self.socket_inactive: self.socket =",
"use clientserver mode to communicate with Vim instance used for debugging. \"\"\" def",
"__init__(self, communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command)",
"prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command class",
"clientserver mode to communicate with Vim instance used for debugging. \"\"\" def __init__(self,",
"# return command class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def __init__(self,",
"= self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if",
"return status == '1' def showFeedback(self, feedback): if not feedback: return feedback_list =",
"# def getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) #",
"command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code =",
"message # code leftover from hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D",
"code leftover from hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue",
"p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout =",
"lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\"",
"from vimpdb import config from vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path",
"(filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result:",
"repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call",
"for debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command)",
"def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue --\\n') # sys.stdout.flush() # sys.stdin.readlines()",
"PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result",
"% repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote()",
"hide last keys sent in VIM command-line command = ''.join((command, ':<BS>')) parts =",
"512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive = True self.port = port",
"self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object): BUFLEN = 512 socket_factory =",
"= True self.port = port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET,",
"waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message",
"def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename =",
"self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive =",
"self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self):",
"vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object):",
"feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' %",
"output = child_stdout.read() return output.strip() def _send(self, command): # add ':<BS>' to hide",
"feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def",
"# add ':<BS>' to hide last keys sent in VIM command-line command =",
"return message # code leftover from hacking # def eat_stdin(self): # sys.stdout.write('-- Type",
"''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code:",
"self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def",
"subprocess from vimpdb import config from vimpdb import errors def get_eggs_paths(): import vim_bridge",
"feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno)",
"command): # add ':<BS>' to hide last keys sent in VIM command-line command",
"Vim knows how to translate them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call",
"mode to communicate with Vim instance used for debugging. \"\"\" def __init__(self, communicator):",
"child_stdout = p.stdout output = child_stdout.read() return output.strip() def _send(self, command): # add",
"last keys sent in VIM command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername',",
"self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename,",
"address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message # code leftover from",
"command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object): BUFLEN = 512",
"= self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\",",
"command class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive",
"\"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result =",
"= False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self,",
"message) return message # code leftover from hacking # def eat_stdin(self): # sys.stdout.write('--",
"keys sent in VIM command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name,",
"translate them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename,",
"self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive =",
"'1' def showFeedback(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call",
"with Vim instance used for debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator",
"\"\"\" def __init__(self, communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\"",
"command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self):",
"does not play well with backslash in filename. # So turn backslash to",
"status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback): if not feedback:",
"import config from vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError())",
"filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def",
"':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise",
"config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result",
"import os import socket import subprocess from vimpdb import config from vimpdb import",
"# command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object): BUFLEN =",
"self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr)",
"showFeedback(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' %",
"socket_factory = socket.socket def __init__(self, port): self.socket_inactive = True self.port = port def",
"self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if",
"expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path =",
"self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object):",
"subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output",
"_showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows command-line does not play well",
"\"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable()",
"self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result # code leftover from hacking #",
"= script self.server_name = server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return",
"# Windows compatibility: # Windows command-line does not play well with backslash in",
"if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port))",
"PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return feedback_list = feedback.splitlines()",
"lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows command-line does not",
"config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self,",
"% (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr)",
"_remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path",
"socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if",
"return output.strip() def _send(self, command): # add ':<BS>' to hide last keys sent",
"def getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) # return",
"feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not",
"parts = self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name,",
"if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch Vim instance",
"ProxyToVim(object): \"\"\" use subprocess to launch Vim instance that use clientserver mode to",
"add ':<BS>' to hide last keys sent in VIM command-line command = ''.join((command,",
"( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name): self.script = script",
"\"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call",
"server_name): self.script = script self.server_name = server_name def prepare_subprocess(self, *args): parts = self.script.split()",
"that use clientserver mode to communicate with Vim instance used for debugging. \"\"\"",
"status == '1' def showFeedback(self, feedback): if not feedback: return feedback_list = feedback.splitlines()",
"= socket.socket def __init__(self, port): self.socket_inactive = True self.port = port def bindSocket(self):",
"socket import subprocess from vimpdb import config from vimpdb import errors def get_eggs_paths():",
"not play well with backslash in filename. # So turn backslash to slash;",
"filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr:",
"return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self)",
"knows how to translate them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\",",
"code leftover from hacking # def getText(self, prompt): # self.setupRemote() # command =",
"errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return (",
"instance used for debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator def _send(self,",
"result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result # code leftover from",
"communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def",
"= communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr):",
"vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script,",
"__init__(self, script, server_name): self.script = script self.server_name = server_name def prepare_subprocess(self, *args): parts",
"def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"return result # code leftover from hacking # def getText(self, prompt): # self.setupRemote()",
"feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback):",
"get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path),",
"= True def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" %",
"% message) return message # code leftover from hacking # def eat_stdin(self): #",
"self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return feedback_list",
"filename. # So turn backslash to slash; Vim knows how to translate them",
"self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive",
"_remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code",
"setupRemote(self): if not self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path,",
"% filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()')",
"% command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): #",
"# code leftover from hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to",
"raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return output.strip() def _send(self, command):",
"leftover from hacking # def eat_stdin(self): # sys.stdout.write('-- Type Ctrl-D to continue --\\n')",
"def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return",
"if not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message, address)",
"% expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result # code",
"lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility: #",
"VIM command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code",
"getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command",
"def _showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows command-line does not play",
"if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def",
"os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths():",
"class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def __init__(self, port): self.socket_inactive =",
"config from vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path",
"if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows compatibility: # Windows",
"child_stdout.read() return output.strip() def _send(self, command): # add ':<BS>' to hide last keys",
"launch Vim instance that use clientserver mode to communicate with Vim instance used",
"in filename. # So turn backslash to slash; Vim knows how to translate",
"to hide last keys sent in VIM command-line command = ''.join((command, ':<BS>')) parts",
"config.logger.debug(\"result: %s\" % result) return result # code leftover from hacking # def",
"with backslash in filename. # So turn backslash to slash; Vim knows how",
"vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class",
"in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\")",
"prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts =",
"socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if not",
"= self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object): BUFLEN = 512 socket_factory",
"return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name): self.script =",
"PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno):",
"'/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\"",
"return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return output.strip() def _send(self,",
"config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not",
"\"\"\" use subprocess to launch Vim instance that use clientserver mode to communicate",
"not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list:",
"not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self,",
"feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call",
"def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr)",
"_send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def",
"leftover from hacking # def getText(self, prompt): # self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")'",
"= subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch",
"self.isRemoteSetup(): # source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command =",
"egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status =",
"self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def",
"if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in",
"True self.port = port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM,",
"result # code leftover from hacking # def getText(self, prompt): # self.setupRemote() #",
"compatibility: # Windows command-line does not play well with backslash in filename. #",
"feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line",
"= self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False",
"def __init__(self, port): self.socket_inactive = True self.port = port def bindSocket(self): if self.socket_inactive:",
"= config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command)",
"output.strip() def _send(self, command): # add ':<BS>' to hide last keys sent in",
"# Windows command-line does not play well with backslash in filename. # So",
"= ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if",
"Windows compatibility: # Windows command-line does not play well with backslash in filename.",
"= p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout output = child_stdout.read() return",
"self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self,",
"command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup(): # source",
"(message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message # code leftover",
"True def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message)",
"= self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class",
"back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def",
"os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name): self.script = script self.server_name",
"source vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\"",
"== '1' def showFeedback(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote()",
"feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list))",
"port def bindSocket(self): if self.socket_inactive: self.socket = self.socket_factory( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"backslash in filename. # So turn backslash to slash; Vim knows how to",
"% repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1'",
"# self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object):",
"return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch Vim instance that",
"def __init__(self, script, server_name): self.script = script self.server_name = server_name def prepare_subprocess(self, *args):",
"def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback): if",
"*args): parts = self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername',",
"def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): #",
"def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE)",
"in VIM command-line command = ''.join((command, ':<BS>')) parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-send\", command)",
"def displayLocals(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>')",
"# code leftover from hacking # def getText(self, prompt): # self.setupRemote() # command",
"showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno): # Windows",
"return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p =",
"filename, lineno): # Windows compatibility: # Windows command-line does not play well with",
"%s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result) return result #",
"feedback.splitlines() self.setupRemote() self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return",
"return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>'",
"= filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr):",
"config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def __init__(self, script, server_name): self.script",
"socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if not self.socket_inactive: self.socket.close()",
"return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to",
"= self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message # code leftover from hacking",
"script self.server_name = server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts",
"self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" %",
"_expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" % result)",
"debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent:",
"self.setupRemote() # command = self._expr('PDB_get_command(\"%s\")' % prompt) # return command class ProxyFromVim(object): BUFLEN",
"class ProxyToVim(object): \"\"\" use subprocess to launch Vim instance that use clientserver mode",
"self._send(':call PDB_show_feedback(%s)<CR>' % repr(feedback_list)) def displayLocals(self, feedback): if not feedback: return feedback_list =",
"vimpdb.vim proxy_package_path = config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" %",
"def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr) result = self._remote_expr(expr) config.logger.debug(\"result: %s\" %",
"= config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return ( os.path.dirname(vimpdb_path), os.path.dirname(vim_bridge_path), ) class Communicator(object): def",
"Windows command-line does not play well with backslash in filename. # So turn",
"prompt) # return command class ProxyFromVim(object): BUFLEN = 512 socket_factory = socket.socket def",
"command) return_code = subprocess.call(parts) if return_code: raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess",
"self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self,",
"PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self,",
"communicator def _send(self, command): self.communicator._send(command) config.logger.debug(\"sent: %s\" % command) def _remote_expr(self, expr): return",
"get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return",
"play well with backslash in filename. # So turn backslash to slash; Vim",
"import subprocess from vimpdb import config from vimpdb import errors def get_eggs_paths(): import",
"= self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback): if not feedback: return",
"config.get_package_path(self) filename = os.path.join(proxy_package_path, \"vimpdb.vim\") command = \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for",
"from vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path =",
"for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status",
"%s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call",
"self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\"",
"displayLocals(self, feedback): if not feedback: return feedback_list = feedback.splitlines() self.setupRemote() self._send(':call PDB_reset_watch()<CR>') for",
"expr) p = subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout",
"self.bindSocket() (message, address) = self.socket.recvfrom(self.BUFLEN) config.logger.debug(\"command: %s\" % message) return message # code",
"lineno): # Windows compatibility: # Windows command-line does not play well with backslash",
"backslash to slash; Vim knows how to translate them back. filename = filename.replace('\\\\',",
"to translate them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' %",
"self.server_name = server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts def",
"Communicator(object): def __init__(self, script, server_name): self.script = script self.server_name = server_name def prepare_subprocess(self,",
"socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self):",
"parts.extend(args) return parts def _remote_expr(self, expr): parts = self.prepare_subprocess('--servername', self.server_name, \"--remote-expr\", expr) p",
"= p.stdout output = child_stdout.read() return output.strip() def _send(self, command): # add ':<BS>'",
"config.logger.debug(\"command: %s\" % message) return message # code leftover from hacking # def",
"for line in feedback_list: self._send(':call PDB_append_watch([%s])<CR>' % repr(line)) def showFileAtLine(self, filename, lineno): if",
"p.stdout output = child_stdout.read() return output.strip() def _send(self, command): # add ':<BS>' to",
"to slash; Vim knows how to translate them back. filename = filename.replace('\\\\', '/')",
"= subprocess.Popen(parts, stdout=subprocess.PIPE) return_code = p.wait() if return_code: raise errors.RemoteUnavailable() child_stdout = p.stdout",
"def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args) return parts def _remote_expr(self, expr): parts",
"= \"<C-\\><C-N>:source %s<CR>\" % filename self._send(command) for egg_path in get_eggs_paths(): self._send(':call PDB_setup_egg(%s)<CR>' %",
"= child_stdout.read() return output.strip() def _send(self, command): # add ':<BS>' to hide last",
"used for debugging. \"\"\" def __init__(self, communicator): self.communicator = communicator def _send(self, command):",
"self.script = script self.server_name = server_name def prepare_subprocess(self, *args): parts = self.script.split() parts.extend(args)",
"% result) return result # code leftover from hacking # def getText(self, prompt):",
"% repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename,",
"repr(line)) def showFileAtLine(self, filename, lineno): if os.path.exists(filename): self._showFileAtLine(filename, lineno) def _showFileAtLine(self, filename, lineno):",
"1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if not self.socket_inactive: self.socket.close() self.socket_inactive",
"import errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged) return",
"raise errors.RemoteUnavailable() class ProxyToVim(object): \"\"\" use subprocess to launch Vim instance that use",
"how to translate them back. filename = filename.replace('\\\\', '/') self.setupRemote() self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>'",
"isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status == '1' def showFeedback(self, feedback): if not",
"self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(('', self.port)) self.socket_inactive = False def closeSocket(self): if not self.socket_inactive:",
"PDB_setup_egg(%s)<CR>' % repr(egg_path)) self._send(':call PDB_init_controller()') def isRemoteSetup(self): status = self._expr(\"exists('*PDB_setup_egg')\") return status ==",
"':<BS>' to hide last keys sent in VIM command-line command = ''.join((command, ':<BS>'))",
"vimpdb import errors def get_eggs_paths(): import vim_bridge vimpdb_path = config.get_package_path(errors.ReturnCodeError()) vim_bridge_path = config.get_package_path(vim_bridge.bridged)",
"slash; Vim knows how to translate them back. filename = filename.replace('\\\\', '/') self.setupRemote()",
"not self.socket_inactive: self.socket.close() self.socket_inactive = True def waitFor(self, pdb): self.bindSocket() (message, address) =",
"self._send(':call PDB_show_file_at_line(\"%s\", \"%d\")<CR>' % (filename, lineno)) def _expr(self, expr): config.logger.debug(\"expr: %s\" % expr)",
"%s\" % command) def _remote_expr(self, expr): return self.communicator._remote_expr(expr) def setupRemote(self): if not self.isRemoteSetup():",
"well with backslash in filename. # So turn backslash to slash; Vim knows",
"turn backslash to slash; Vim knows how to translate them back. filename ="
] |
[
"drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name = 'drf_file_management' urlpatterns =",
"from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name = 'drf_file_management' urlpatterns",
"routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name = 'drf_file_management'",
"import path, include from rest_framework import routers from drf_file_management.views import FileAPIView router =",
"django.urls import path, include from rest_framework import routers from drf_file_management.views import FileAPIView router",
"path, include from rest_framework import routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter()",
"rest_framework import routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name",
"import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name = 'drf_file_management' urlpatterns = router.urls",
"from rest_framework import routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView)",
"include from rest_framework import routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file',",
"from django.urls import path, include from rest_framework import routers from drf_file_management.views import FileAPIView",
"import routers from drf_file_management.views import FileAPIView router = routers.SimpleRouter() router.register(r'file', FileAPIView) app_name ="
] |
[
"branch_labels = None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage',",
"\"\"\"Upgrade to 2.0.0 Revision ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\"",
"<gh_stars>10-100 \"\"\"Upgrade to 2.0.0 Revision ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327",
"used by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on",
"sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>'",
"as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision =",
"sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def downgrade(): op.drop_column('flask_usage', 'track_var') op.drop_column('flask_usage', 'username')",
"2018-04-25 09:39:38.879327 \"\"\" from alembic import op import sqlalchemy as sa # revision",
"= '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on = None def upgrade():",
"None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def downgrade():",
"def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def downgrade(): op.drop_column('flask_usage',",
"import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision",
"None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128),",
"op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def downgrade(): op.drop_column('flask_usage', 'track_var') op.drop_column('flask_usage',",
"revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on = None def",
"depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True))",
"Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op import sqlalchemy as sa",
"by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on =",
"<KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op import",
"alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic.",
"= None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def",
"upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username', sa.String(128), nullable=True)) def downgrade(): op.drop_column('flask_usage', 'track_var')",
"2.0.0 Revision ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic",
"revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels =",
"0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op import sqlalchemy as",
"to 2.0.0 Revision ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from",
"= None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True)) op.add_column('flask_usage', sa.Column('username',",
"ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op",
"import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>'",
"from alembic import op import sqlalchemy as sa # revision identifiers, used by",
"= '0<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128),",
"# revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels",
"down_revision = '0<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var',",
"09:39:38.879327 \"\"\" from alembic import op import sqlalchemy as sa # revision identifiers,",
"\"\"\" from alembic import op import sqlalchemy as sa # revision identifiers, used",
"op import sqlalchemy as sa # revision identifiers, used by Alembic. revision =",
"'<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.add_column('flask_usage',",
"Revision ID: <KEY> Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import",
"Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None depends_on = None",
"identifiers, used by Alembic. revision = '<KEY>' down_revision = '0<PASSWORD>' branch_labels = None",
"sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision",
"Revises: 0<PASSWORD> Create Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op import sqlalchemy",
"Date: 2018-04-25 09:39:38.879327 \"\"\" from alembic import op import sqlalchemy as sa #",
"'0<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.add_column('flask_usage', sa.Column('track_var', sa.String(128), nullable=True))"
] |